topic:
To give you a head node list head, you write code sequence repeatedly deleting the list by the sum of node 0 is composed of a continuous, until no such sequences.
After deleting is complete, you return to the first node of the final results list.
You can return any answer to meet the requirements of the subject.
(Note that all sequences in the following examples, are serialized representation of objects ListNode.)
Example 1:
Input: head = [1,2, -3,3,1]
Output: [3,1]
Tip: Answer [1,2,1] is correct.
Example 2:
Input: head = [1,2,3, -3,4]
Output: [1,2,4]
Example 3:
Input: head = [1,2,3, -3, -2]
Output: [1]
prompt:
Give your list may have 1-1000 node.
For each node in the linked list, the node values: -1000 <= node.val <= 1000 .
Ideas:
The same prefix and prefix memory, and searching, and that the corresponding section is a length of zero.
Code:
class Solution {
public:
ListNode* removeZeroSumSublists(ListNode* head) {
int s[1005] = { 0 }, k = 0; //s是链表前缀和,k是链表长度
ListNode*p = head, *list[1005];
while (p)
{
list[++k] = p, s[k] = p->val + s[k - 1], p = p->next;
}
for (int i = 0; i < k; i++)
{
for (int j = k; j > i; j--)
{
if (s[i] != s[j])continue;
if (i == 0)head = list[j]->next;
else list[i]->next = list[j]->next;
i = j;
}
}
return head;
}
};