方法一:
用一个指针来操作head节点,最好不要直接操作head节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode Head=new ListNode(0);
Head.next=head;
ListNode first=head;
int length=0;
while(first!=null){
first=first.next;
length++;
}
int count=length-n;
first=Head;
while(count>0){
count--;
first=first.next;
}
first.next=first.next.next;
return Head.next;
}
}
方法二:
官方给的优化后的j解法。
为只使用一次遍历。我们可以使用两个指针而不是一个指针。
第一个指针从列表的开头向前移动 n+1 步,而第二个指针将从列表的开头出发。
现在,这两个指针被 n个结点分开。我们通过同时移动两个指针向前来保持这个
恒定的间隔,直到第一个指针到达最后一个结点。此时第二个指针将指向从最后
一个结点数起的第 n个结点。我们重新链接第二个指针所引用的结点的 next
指针
指向该结点的下下个结点。
图示如下:
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode Head=new ListNode(0);
Head.next=head;
ListNode first=Head;
ListNode second=Head;
for(int i=0;i<n+1;i++){
first=first.next;
}
while(first!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return Head.next;
}
}