LC_19. Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
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.
//time: o(n) space: o(1)
 1 //先走N 步,然后用TWO POINTERS 的思想做出来
 2     /*
 3     *       1->2->3->4->5->null
 4     *   d
 5     *   s        (s)
 6     *             f         (f)
 7     * */
 8     public ListNode removeNthFromEnd(ListNode head, int n) {
 9         ListNode dummy = new ListNode(0);
10         ListNode slow = dummy;
11         ListNode fast = dummy;
12         dummy.next = head ;
13         //当N = 2 :0->1 1->2 2->3 FAST 走了三步
14         for (int i = 0; i <=n ; i++) {
15             fast = fast.next ;
16         }
17         //0->1 1->2 2->3 SLOW 走了三步  3->4 4->5 5-> null FAST 走了3步
18         while (fast != null){
19             slow = slow.next ;
20             fast = fast.next ;
21         }
22         //直接跳过去
23         slow.next = slow.next.next ;
24         return dummy.next ;
25     }
原文地址:https://www.cnblogs.com/davidnyc/p/8457909.html