Leetcode 19——Remove Nth Node From End of List

时间:2023-03-09 03:04:16
Leetcode 19——Remove Nth Node From End of List

  Given a linked list, remove the nth node from the end of list and return its head.

  For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.

  Note:
  Given n will always be valid.
  Try to do this in one pass.

删除给定的倒数的第n个节点。我想的是数一遍这个ListNode的长度,然后减去n,再删除。上代码:

public static ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null)return head; int length=0;
ListNode headCopy1=head;
ListNode headCopy2=head;
//calculate length
while(headCopy1!=null) {
length++;
headCopy1=headCopy1.next;
}
//remove first node,return head.next
if(n==length)return head.next; for(int i=0;i<(length-n-1);i++) {
headCopy2=headCopy2.next;
}
if(headCopy2.next.next==null) {
headCopy2.next=null;
}else {
headCopy2.next=headCopy2.next.next;
}
return head;
}

后面看了别人的思路,采用的是快慢指针,先在head前面加一个节点start,这个很重要,如果只有一个节点,且要删除这个节点,虽然可以直接返回null,但是在统一性上来说,就多了几行单独出来的代码,快慢指针都指向这个start。快指针先走,走n步,然后再让快慢指针一起走,直到快指针为null,这时候慢指针后面的即为要删除的,通过快慢指针实现了计算length-n,很巧妙。然后让next跳过一个节点即可。再有就是最后的返回值,一开始我以为返回head和start.next都可以,结果我用head来返回的时候就报错了。因为head始终指的是头节点,即使头节点删除了,也还是会返回值,而start这个节点是与返回值无关的一个节点,对start不会有任何操作,如果只有一个节点即head节点,且要删除这个节点,你再返回head就不对了,而返回start.next则为空。

public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start=new ListNode(0);
start.next=head;
ListNode fast,slow;
fast=slow=start; for(int i=0;i<n+1;i++) {
fast=fast.next;
}
while(fast!=null) {
slow=slow.next;
fast=fast.next;
}
slow.next=slow.next.next;
return start.next;
//return head;
}