问题链接
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);
}
}