203. Remove Linked List Elements【easy】
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
解法一:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 if (head == NULL) { 13 return head; 14 } 15 16 ListNode * dummy = new ListNode(INT_MIN); 17 dummy->next = head; 18 head = dummy; 19 20 while (head != NULL && head->next != NULL) { 21 if (head->next->val == val) { 22 while (head->next != NULL && head->next->val == val) { 23 ListNode * temp = head->next; 24 free(temp); 25 head->next = head->next->next; 26 } 27 } 28 else { 29 head = head->next; 30 } 31 } 32 33 return dummy->next; 34 } 35 };
里面的while可以不用,因为这个题和(82. Remove Duplicates from Sorted List II)不一样,那个题你根本不知道val是什么,所以只用一个if是不行的。但是这个题你知道val是什么,所以可以省略里面的while。
解法二:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeElements(ListNode* head, int val) { 12 if (head == NULL) { 13 return head; 14 } 15 16 ListNode * dummy = new ListNode(INT_MIN); 17 dummy->next = head; 18 head = dummy; 19 20 while (head != NULL && head->next != NULL) { 21 if (head->next->val == val) { 22 ListNode * temp = head->next; 23 free(temp); 24 head->next = head->next->next; 25 } 26 else { 27 head = head->next; 28 } 29 } 30 31 return dummy->next; 32 } 33 };
精简写法
解法三:
1 public ListNode removeElements(ListNode head, int val) { 2 if (head == null) return null; 3 head.next = removeElements(head.next, val); 4 return head.val == val ? head.next : head; 5 }
递归,参考了@renzid 的代码