203. Remove Linked List Elements【easy】

时间:2022-06-03 12:33:55

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.

解法一:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL) {
return head;
} ListNode * dummy = new ListNode(INT_MIN);
dummy->next = head;
head = dummy; while (head != NULL && head->next != NULL) {
if (head->next->val == val) {
while (head->next != NULL && head->next->val == val) {
ListNode * temp = head->next;
free(temp);
head->next = head->next->next;
}
}
else {
head = head->next;
}
} return dummy->next;
}
};

里面的while可以不用,因为这个题和(82. Remove Duplicates from Sorted List II)不一样,那个题你根本不知道val是什么,所以只用一个if是不行的。但是这个题你知道val是什么,所以可以省略里面的while。

解法二:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (head == NULL) {
return head;
} ListNode * dummy = new ListNode(INT_MIN);
dummy->next = head;
head = dummy; while (head != NULL && head->next != NULL) {
if (head->next->val == val) {
ListNode * temp = head->next;
free(temp);
head->next = head->next->next;
}
else {
head = head->next;
}
} return dummy->next;
}
};

精简写法

解法三:

 public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}

递归,参考了@renzid 的代码