从链表中删去总和值为零的连续节点(leetcode 1171)


一:解题思路

采用递归的思想来做。

二:完整代码示例 (C++版和Java版)

C++代码如下:

class Solution {
public:
    ListNode* removeZeroSumSublists(ListNode* head) 
    {
        if (head == NULL) return NULL;
        ListNode* p = head;
        int sum = 0;

        while (p != NULL)
        {
            sum += p->val;
            p = p->next;
            if (sum == 0) return removeZeroSumSublists(p);
        }

        head->next = removeZeroSumSublists(head->next);

        return head;
    }
};