public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode next=new ListNode(-1);
next.next=head;
ListNode pre=head,post=head;
//移动五次
while(n-->0)
pre=pre.next;
while(pre!=null){
pre=pre.next;
post=post.next;
}
if(post.next!=null){
post.val=post.next.val;
post.next=post.next.next;
}else{
post = null;
}
return next.next;
}
怎么改都不对啊……出错就出在只有一个节点 n=1的情况,不能返回null。
但,其实返回倒数第K个节点,就是下列方法。按照这个方法来写,必须考虑上述问题。
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null)
return null;
ListNode P1 = head;
while (P1 != null && k-- > 0)
P1 = P1.next;
if (k > 0)
return null;
ListNode P2 = head;
while (P1 != null) {
P1 = P1.next;
P2 = P2.next;
}
return P2;
}
我这个方法是咋整都不行了,就只能是找别人的方法了。
下面这个方法实在是厉害了,非常灵活。因为后走的这个指针走到的是要删除节点的前一个节点,因为他是重新加了一个newHead,所以不需要考虑要删除节点是原链表头节点的情况,和尾节点的情况……
但是要注意,因为要使后走的指针指向前一个节点,所以前后指针的差距应该是(n+1)
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode first = dummy;
ListNode second = dummy;
// Advances first pointer so that the gap between first and second is n nodes apart
for (int i = 1; i <= n + 1; i++) {
first = first.next;
}
// Move first to the end, maintaining the gap
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
return dummy.next;
}