Day28: [LeetCode中等] 1171. 從鏈表中刪去總和值爲零的連續節點

Day28: [LeetCode中等] 1171. 從鏈表中刪去總和值爲零的連續節點

題源:

來自leetcode題庫:

https://leetcode-cn.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/

思路:

遍歷鏈表,算出前置和,依次放進set裏,然後遇到相同的的話,就會知道,這兩個相同的前置和之間的值的總和就是0了。循環這個過程即可

代碼:

dirty code湊合看吧

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeZeroSumSublists(ListNode* head) {
        if(!head) return head;
        bool succ=true;
        while(1){
            succ=true;
            unordered_map<int,ListNode*> m;
            ListNode *res=NULL;
            m.insert(make_pair(0,res));
            auto p=head;
            int sum=0;
            while(p){
                sum+=p->val;
                if(m.find(sum)==m.end()){
                    m.insert(make_pair(sum,p));
                }else{
                    succ=false;
                    if(sum==0){
                        res=p->next;
                        head=res;
                    }else{
                        m[sum]->next=p->next;
                    }
                    break;
                }
                p=p->next;
            }
            if(succ==true) break;
        }return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章