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
解题思路:基本的链表删除操作,没啥思路。就是要注意删除第一个元素的情况。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
while(head && head->val == val) head = head->next;
struct ListNode* last = head;
struct ListNode* now = head;
while(now){
if(now->val == val){
last->next = now->next;
free(now);
now = last->next;
}else{
last = now;
now = now->next;
}
}
return head;
}