zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    PHP 文件上传
    浅析文件上传漏洞
    JS之Number类
    JS之String类
    Java中的多态
    JS之数据类型
    JavaScript的组成
    双向链表与LRU算法实现
    字符串比较--小问题大智慧
    龙生九子-浅谈Java的继承
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8457909.html
Copyright © 2011-2022 走看看