forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
203.c
92 lines (73 loc) · 1.62 KB
/
203.c
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode *ret;
struct ListNode *prev, *p;
ret = p = head;
prev = head;
while (p) {
if (p->val == val) {
if (p == ret) { /* head */
ret = p->next;
prev = ret; /* maybe useless */
}
else { /* NOT head */
prev->next = p->next;
}
}
else {
prev = p;
}
p = p->next;
}
return ret;
}
int main() {
struct ListNode *l1 = (struct ListNode *)calloc(9, sizeof(struct ListNode));
struct ListNode *p = l1;
p->val = 6;
p->next = l1 + 1;
p = p->next;
p->val = 6;
p->next = l1 + 2;
p = p->next;
p->val = 1;
p->next = l1 + 3;
p = p->next;
p->val = 6;
p->next = l1 + 4;
p = p->next;
p->val = 6;
p->next = l1 + 5;
p = p->next;
p->val = 6;
p->next = l1 + 6;
p = p->next;
p->val = 2;
p->next = l1 + 7;
p = p->next;
p->val = 3;
p->next = l1 + 8;
p = p->next;
p->val = 6;
p->next = NULL;
/* 6 -> 6 -> 1 -> 6 -> 6 -> 6 -> 2 -> 3 -> 6 */
p = l1;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
p = removeElements(l1, 6);
/* 1 -> 2 -> 3 */
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}