zoukankan      html  css  js  c++  java
  • 19. Remove Nth Node From End of List

    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.

    Follow up:

    Could you do this in one pass?

    AC code:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* removeNthFromEnd(ListNode* head, int n) {
            ListNode* demo = new ListNode(0);
            demo->next = head;
            ListNode* fast = demo;
            ListNode* slow = demo;
            
            for (int i = 0; i < n; ++i) {
                fast = fast->next;
            }
            while (fast->next) {
                slow = slow->next;
                fast = fast->next;
            }
            slow->next = slow->next->next;
            return demo->next;
        }
    };
    

    Runtime: 8 ms, faster than 34.35% of C++ online submissions for Remove Nth Node From End of List.

    step1:
    
             1 -> 2 -> 3 -> 4 -> 5
    
    demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5
    
    fast:              /
    
    slow:       /
    
     
    
    step2:
    
             1 -> 2 -> 3 -> 4 -> 5
    
    demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5
    
    fast:               /
    
    slow:         /
    
     
    
    step3:
    
             1 -> 2 -> 3 -> 4 -> 5
    
    demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5
    
    fast:                 /
    
    slow:           /
    
     
    
    step4:
    
             1 -> 2 -> 3 -> 4 -> 5
    
    demo:  0 -> 1 -> 2 -> 3 -> 4 -> 5
    
    fast:                   /
    
    slow:             /
    
     
    
    step5:
    
    fast->next == null
    
    slow->next = slow->next->next;
    
     
    
             1 -> 2 -> 3 -> 4 -> 5
    
    demo:  0 -> 1 -> 2 -> 3     4 -> 5
    
    fast:               |     /|
    
    slow:              |      |
    
                     |_______|
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    地址标记,SpringMVC转发与调用相关知识存档
    SpringMVC+MyBatis项目分析与开发实例
    程序开发思路
    web.xml相关知识摘录整理
    Spring AOP
    Spring+Struts2/Hibernate 学习笔记
    Spring学习笔记 Part.01
    用java实现简单TCP服务器监听
    c语言希尔排序,并输出结果(不含插入排序)
    用java实现AVL树并打印结果
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9741047.html
Copyright © 2011-2022 走看看