1. 程式人生 > >203. Remove Linked List Elements【easy】

203. Remove Linked List Elements【easy】

value use ati question have desc att mat .cn

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 的代碼

203. Remove Linked List Elements【easy】