利用map记录数组的前缀和,然后再遍历一次, trans ->next = map[sum]->next;语句完成了去除总和值为0的连续节点,如果当前节点不能满足总和值为0的连续节点,trans->next指向当前节点的下一个节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
unordered_map<int, ListNode*> map;
ListNode* t = new ListNode(0, head);
int sum = 0;
ListNode* trans = t;
while(trans != nullptr){
sum += trans->val;
map[sum] = trans;
trans = trans->next;
}
sum = 0;
trans = t;
while(trans != nullptr){
sum += trans->val;
trans ->next = map[sum]->next;
trans = trans ->next;
}
return t->next;
}
};