---
title: 'LeetCode 203. Remove Linked List Elements'
disqus: hackmd
---
# LeetCode 203. Remove Linked List Elements
## Description
Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.
## Example
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
## Constraints
The number of nodes in the list is in the range [0, 10^4^].
1 <= Node.val <= 50
0 <= val <= 50
## Answer
此題先抓出第一非目標點當頭,再一一往下檢查誰要刪除。注意不要檢查完一次就馬上往下推,而是確認下一點不為目標才往下走,所以為防止替換完的點仍為目標點,所以我們換完之後不馬上往下走,而是在做一次檢查,確保不是連續的目標點。
```Cin=
//0222_03_12
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode * opr = head, *del = NULL;
while(opr != NULL && opr->val == val){
del = opr;
opr = opr->next;
free(del);
}
head = opr;
while(opr != NULL && opr->next != NULL){
if(opr->next->val == val){
del = opr->next;
opr->next = del->next;
free(del);
}
else{
opr = opr->next;
}
}
return head;
}
```
## Link
https://leetcode.com/problems/remove-linked-list-elements/
###### tags: `Leetcode`