We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents f66dc4e + 68e7126 commit 51d3ea3Copy full SHA for 51d3ea3
remove-linked-list-elements.cc
@@ -2,18 +2,21 @@
2
class Solution {
3
public:
4
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;
+ ListNode *y=x, **last_p = &x;
+ //invariant:
+ // y: point to enumerate
+ // last_p: points to the pointer from which we come to y last time
+ // (can be list head)
+
11
+ while (y)
12
+ if (y->val == val) {
13
+ *last_p = y->next;
14
+ delete y;
15
+ y = *last_p;
16
} else {
- *y = x;
- y = &x->next;
- x = x->next;
17
+ last_p = &y->next;
18
+ y = y->next;
19
}
- *y = 0;
- return yy;
20
+ return x;
21
22
};
0 commit comments