Skip to content

Commit 51d3ea3

Browse files
committed
Merge remote-tracking branch 'ir193/maskray'
2 parents f66dc4e + 68e7126 commit 51d3ea3

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

remove-linked-list-elements.cc

+14-11
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,21 @@
22
class Solution {
33
public:
44
ListNode* removeElements(ListNode* x, int val) {
5-
ListNode *yy, **y = &yy, *t;
6-
while (x)
7-
if (x->val == val) {
8-
t = x->next;
9-
delete x;
10-
x = t;
5+
ListNode *y=x, **last_p = &x;
6+
//invariant:
7+
// y: point to enumerate
8+
// last_p: points to the pointer from which we come to y last time
9+
// (can be list head)
10+
11+
while (y)
12+
if (y->val == val) {
13+
*last_p = y->next;
14+
delete y;
15+
y = *last_p;
1116
} else {
12-
*y = x;
13-
y = &x->next;
14-
x = x->next;
17+
last_p = &y->next;
18+
y = y->next;
1519
}
16-
*y = 0;
17-
return yy;
20+
return x;
1821
}
1922
};

0 commit comments

Comments
 (0)