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

    题目:

    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.

    提示:

    此题可以通过双指针(两个指针之间相差n个间隔),这样可以保证一次遍历链表就完成题目中的要求。

    有一些需要注意的地方:

    • 被删去的节点记得要释放资源;
    • 可以创建一个指向head的节点,然后初始状态下双指针均指向创建的这个节点,这样做可以让算法可以处理删除head节点的情况。

    代码:

    /**
     * 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) 
        {
            if (!head) return nullptr;
    
            ListNode new_head(-1);
            new_head.next = head;
    
            ListNode *slow = &new_head, *fast = &new_head;
    
            for (int i = 0; i < n; i++)
                fast = fast->next;
    
            while (fast->next) 
            {
                fast = fast->next;
                slow = slow->next;
            }
    
            ListNode *to_be_deleted = slow->next;
            slow->next = slow->next->next;
    
            delete to_be_deleted;
    
            return new_head.next;
        }
    };
  • 相关阅读:
    mysql 内联接、左联接、右联接、完全联接、交叉联接 区别
    JS 时间字符串与时间戳之间的转换
    MySQL性能优化的最佳20条经验
    ++i 与 i++ 的区别
    === 与 == 区别
    SC命令创建和删除windows服务
    杂记
    linux 文件编程
    u-boot 启动过程
    简单冒泡法
  • 原文地址:https://www.cnblogs.com/jdneo/p/4755913.html
Copyright © 2011-2022 走看看