# 203. Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example:

``````Input:  1->2->6->3->4->5->6, val = 6
Output: 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*p=head->next,*q=head;
while(p!=NULL){
if(p->val==val){
q->next=p->next;
free(p);
p=q->next;
}
else{
q=q->next;
p=p->next;
}
}
if(head->val==val){
p=head;
head=head->next;
free(p);
}
return head;
}``````

``````/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/

struct ListNode* removeElements(struct ListNode* head, int val){

if (head == NULL) {
return;
}
struct ListNode* pPre = NULL;
struct ListNode* pCur = head;
while (pCur) {
if (pCur->val == val) {
if (pPre == NULL) {//或设置为if(head->val == val)
head = pCur->next;
free(pCur);
pCur = head;
}
else {
pPre->next = pCur->next;
free(pCur);
pCur = pPre->next;
}
}
else {
pPre = pCur;
pCur = pCur->next;
}
}
return head;
}``````

``````执行时间60ms
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {

if(head == NULL ) return head;

head->next =  removeElements( head->next, val);

if(head->val == val)
{
struct ListNode* p = NULL;
p = head->next;
free(head);
head = p;
}

return head;

}``````