原题链接https://leetcode.com/problems/remove-linked-list-elements/
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 NULL;
ListNode *pre, *current;
pre = head;
current = head->next;
while (pre != NULL && pre->val == val)
{
pre = current;
if (pre != NULL)
current = pre->next;
}
head = pre;
while (current != NULL)
{
if (current->val == val)
pre->next = current->next;
else
pre = current;
current = current->next;
}
return head;
}
};