• 【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;
        }
    };
  • 相关阅读:
    HDU1720 A+B Coming
    HDU1390 ZOJ1383 Binary Numbers
    HDU1390 ZOJ1383 Binary Numbers
    HDU2504 又见GCD
    HDU2504 又见GCD
    HDU1335 POJ1546 UVA389 UVALive5306 ZOJ1334 Basically Speaking
    HDU1335 POJ1546 UVA389 UVALive5306 ZOJ1334 Basically Speaking
    HDU1020 ZOJ2478 Encoding
    HDU1020 ZOJ2478 Encoding
    HDU2097 Sky数
  • 原文地址:https://www.cnblogs.com/jdneo/p/4755913.html
Copyright © 2020-2023  润新知