题目:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode * current, *pre;
current = pre = head;
while(current != NULL ){
while(current != NULL && current->val == val) {
if(current == head) {
current = current->next;
head = head->next;
} else {
pre->next = current->next;
current = current->next;
}
}
pre = current;
if(current != NULL)
current = current->next;
}
return head;
}