-
Notifications
You must be signed in to change notification settings - Fork 1
/
remove-zero-sum-consecutive-nodes-from-linked-list.php
54 lines (45 loc) · 1.32 KB
/
remove-zero-sum-consecutive-nodes-from-linked-list.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
require 'list_node.php';
class Solution {
/**
* @param ListNode $head
* @return ListNode
*/
function removeZeroSumSublists($head) {
$dummy = new ListNode(0);
$dummy->next = $head;
$prefixSum = [];
$p = $dummy->next;
$count = 0;
while (!is_null($p)) {
$count += $p->val;
if (isset($prefixSum[$count])) {
$tmpNode = $prefixSum[$count]->next;
$node = $prefixSum[$count];
$node->next = $p->next;
// 消除
$tmpCount = $count;
while ($tmpNode !== $p) {
$tmpCount += $tmpNode->val;
if ($tmpCount !== $count) {
unset($prefixSum[$tmpCount]);
}
$tmpNode = $tmpNode->next;
}
} elseif ($count === 0) {
$dummy->next = $p->next;
$prefixSum = [];
} else {
$prefixSum[$count] = $p;
}
$p = $p->next;
}
return $dummy->next;
}
}
//$head = make([1,2,3,-3,-2]);
//$head = make([1,-1]);
$head = make([1,3,2,-3,-2,5,5,-5,1]);
//$head = make([1,0,-1,2,-1,0]);
$ret = (new Solution())->removeZeroSumSublists($head);
printList($ret);