zoukankan      html  css  js  c++  java
  • LeetCode OJ-- Remove Nth Node From End of List

    https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/

    remove倒数第n个节点

    一般list remove node的题目,都要先设置一个 dummy 节点, dummy->next = head,最后返回 dummy->next。

    因为有可能要删除的就是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==NULL || n<=0)
                return head;
            
            ListNode *dummy = new ListNode(-1);
            dummy->next = head;
            ListNode *fast = dummy, *slow = dummy;
        
            while(n--)
            {
                if(fast == NULL)
                    return dummy->next;
                fast = fast->next;
            }
            while(fast->next)
            {
                fast = fast->next;
                slow = slow->next;
            }
            if(slow->next)
                slow->next = slow->next->next;
                
            return dummy->next;
        }
    };
  • 相关阅读:
    poj1703--Find them, Catch them
    poj2828--Buy Tickets
    POJ 2594 Treasure Exploration(Floyd+最小路径覆盖)
    HDU
    二分图的一些性质
    HDU
    POJ 1659 Frogs' Neighborhood (Havel定理构造图)
    HDU
    HDU
    2018 Multi-University Training Contest 1
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3829029.html
Copyright © 2011-2022 走看看