給你一個鏈表的頭節點 head,請你編寫代碼,反覆刪去鏈表中由 總和 值爲 0 的連續節點組成的序列,直到不存在這樣的序列爲止。
刪除完畢後,請你返回最終結果鏈表的頭節點。
簡要題解;
暴力遍歷每一段然後當前段爲0的話就把段頭指針指向段尾的下一個節點。代碼如下:
/**
* 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) {
ListNode* cur=new ListNode(0);
ListNode* pre=cur;
cur->next=head;
while(cur!=NULL)
{
ListNode *tem=cur->next;
int sum=0;
while(tem!=NULL)
{
sum+=tem->val;
tem=tem->next;
if(sum==0)
{
cur->next=tem;
break;
}
}
if(tem==NULL) cur=cur->next;
}
return pre->next;
}
};