LC_19. Remove Nth Node From End of List

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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     }

 

以上是关于LC_19. Remove Nth Node From End of List的主要内容,如果未能解决你的问题,请参考以下文章

41.leetcode19_remove_nth_node_from_end_of_list

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

19. Remove Nth Node From End of List