题目
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) {
if(head==NULL){
return NULL;
}
struct ListNode* cur=head;
struct ListNode* pre=NULL;
struct ListNode* next=NULL;
while(cur!=NULL){
next=cur->next;
if(cur->val==val){
cur->next=NULL;
if(pre!=NULL){
pre->next=next;
}
else{
head=next;
}
cur=next;
}
else{
pre=cur;
cur=next;
}
}
return head;
}