问题描述:
Remove all elements from a linked list of integers that have value val.
示例:
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
问题分析:
给一个头结点thead连接head,然后依次遍历结点,找到值相同的结点,删除即可。
过程详见代码:
/**
* 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 thead(0);
thead.next = head;
ListNode* last = &thead;
while(head)
{
if(head->val == val)
{
last->next = head->next;
}
else
{
last = head;
}
head = head->next;
}
return thead.next;
}
};