LeetCode 203: Remove Linked List Elements

Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6. Return: 1 --> 2 --> 3 --> 4 --> 5.

思路

两个指针, 一样的就删, 不一样就next.

代码

C语言版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* dummy;
dummy -> next = head;
struct ListNode* p = dummy;
struct ListNode* q = head;
while(q != NULL) {
if(q->val == val) {
p->next = q->next;
} else {
p = p->next;
}
q = q->next;
}
return dummy->next;
}

63 / 63 test cases passed.
Status: Accepted
Runtime: 12 ms

1
2
3
4
5
6
7
8
st=>start: Start
e=>end
op=>operation: My Operation
cond=>condition: Yes or No?
st->op->cond
cond(yes)->e
cond(no)->op
1
2
3
Alice->Bob: Hello Bob, how are you?
Note right of Bob: Bob thinks
Bob-->Alice: I am good thanks!
分享到 评论