# Leetcode 203. Remove Linked List Elements ###### tags: `Leetcode` 題目 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 1: Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5] Example 2: Input: head = [], val = 1 Output: [] Example 3: Input: head = [7,7,7,7], val = 7 Output: [] 解法: 1.主要判斷的就是當下val是否有等於val,設定一個pre跟一個cur指標 2.再來就是第一個他沒有pre怎麼辦,自己多加一個在他前面,struct ListNode* tmp,tmp->next = head,讓pre = tmp; cur = head 3.記得最後要回傳的是pre->next,因為pre是自己多加的,真正的開頭是pre->next ====================== ``` /** * 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* tmp = malloc(sizeof(struct ListNode)); tmp->next = head; struct ListNode* pre = tmp; struct ListNode* cur = head; while(cur != NULL) { if(cur->val == val) pre->next = cur->next; else pre = cur; cur = cur->next; } return tmp->next; */ if(head == NULL) return NULL; if(head->val == val) return removeElements(head->next, val); else head->next = removeElements(head->next, val); return head; } ```