编辑
Remove Nth Node From End of List
本文访问次数:0
  1. 1. 问题链接
  2. 2. 问题描述
  3. 3. 解决办法

问题链接

Remove Nth Node From End of List | LeetCode OJ

问题描述

移除给定列表的倒数第N个节点并返回列表头。

解决办法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode previousNode = null;
        ListNode targetNode = null;
        ListNode nextNode = null;
        ListNode node = head;
        List<ListNode>list= new ArrayList();
        list.add(node);
        int length = 1;
        while(node.next != null){
            list.add(node.next);
            node = node.next;
            length ++;
        }
        int previousPosition = length - n - 1;
        int targetPosition = length - n;
        int nextPosition = length - n + 1;

        if(targetPosition == 0){
            return head.next;
        }

        previousNode = list.get(previousPosition);
        targetNode = list.get(targetPosition);
        if(nextPosition < length){
            nextNode = list.get(nextPosition);
        }

        previousNode.next = nextNode;
        return list.get(0);
    }
}
没有任何评论