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;
    }
};
发布了49 篇原创文章 · 获赞 13 · 访问量 520

猜你喜欢

转载自blog.csdn.net/qq2215459786/article/details/103284260