0%

删除链表中的元素

删除链表中等于给定值 val 的所有元素。

示例
给定: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
返回: 1 –> 2 –> 3 –> 4 –> 5

解答:

1
2
3
4
5
6
7
8
9
10
11
12
13
ListNode* removeElements(ListNode* head, int val) {
ListNode* preHead = new ListNode(-1);
ListNode* cur = preHead;
while (head) {
if (head->val != val) {
auto item = new ListNode(head->val);
cur->next = item;
cur = item;
}
head = head->next;
}
return preHead->next;
}

它山之石

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ListNode* removeElements(ListNode* head, int val) {
if (!head) return head;
ListNode* h = head;
while (h && h->next) {
if (h->next->val == val) {
ListNode* temp = h->next;
h->next = h->next->next;
delete temp;
}
else h = h->next;
}

if (head->val == val) head = head->next;
return head;
}