题目:
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
题意:
删除链表中元素值等于某个值的所有节点。
代码如下:
/**
* 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* first = NULL;
ListNode* curr = head;
ListNode* h = NULL;
while (curr != NULL) {
if (curr->val == val) {
if (first != NULL)
first->next = curr->next;
}
else {
first = curr;
if (h == NULL)h = first;
}
curr = curr->next;
}
return h;
}
};