Given a linked list, remove the n-th node from the end of list and return its head.
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.
code1:
public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null) return null; ListNode number=head; ListNode fast=head; ListNode slow=head; ListNode pre=null; int count=1; while(number.next!=null){ number=number.next; count++; } if(count==n) return head.next; for(int i=0;i<n;i++) fast=fast.next; while(fast!=null){ fast=fast.next; pre=slow; slow=slow.next; } pre.next=slow.next; return head; }
code2:(优化后的)
public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null) return null; ListNode number=head; ListNode slow=head; int count=1; while(number.next!=null){ number=number.next; count++; } if(count==n) return head.next; int step=count-n; while(step>1){ slow=slow.next; step--; } slow.next=slow.next.next; return head; }