1. 每一轮,如果有可以删除的(和为0),则删除,并从头开始遍历;如果没有可以删除的,则右移left。
class Solution { public: ListNode* removeZeroSumSublists(ListNode* head) { head=reverseList(head); ListNode ln(0);ln.next=head; ListNode *left=head,*lpre=&ln,*right=head; while(left) { right=left; int sum=0; while(right) { sum+=right->val; if(sum==0) { lpre->next=right->next; /*while(left!=lpre->next) { ListNode* tmp=left->next; delete left; left=tmp; }*/ 不能释放这些空间,如果释放,不能通过测试用例[0],报heap-use-after-free错误。 break; } else { right=right->next; } }//while if(right) {lpre=&ln;left=ln.next;} else {lpre=left;left=left->next;} }//while head=reverseList(ln.next); return head; } ListNode* reverseList(ListNode* head) { ListNode *pre=nullptr,*cur=head,*next=head; while(cur) { next=cur->next; cur->next=pre; pre=cur; cur=next; } return pre; } };
删除之后,继续遍历时,删除的情况比如:-3 3 -2 2
class Solution { public: ListNode* removeZeroSumSublists(ListNode* head) { ListNode ln(0);ln.next=head; ListNode* pre=&ln,*right=head; int sum=0; while(right) { sum+=right->val; if(sum==0) pre->next=right->next; right=right->next; if(!right) { pre=pre->next; if(!pre) break; right=pre->next; sum=0; } } return ln.next; } };
3. 递归
class Solution { public: ListNode* removeZeroSumSublists(ListNode* head) { if(!head) return head; ListNode* ans=removeZeroSumSublists(head->next); head->next=ans; int sum=head->val; if(sum==0) { head->next=nullptr; return ans; } ListNode* node=head->next; while(node) { sum+=node->val; if(sum==0) { return node->next; } node=node->next; } return head; } };