题目:
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.
解答:
需要添加一个phead,防止删除第一个的情况,同时需要检验next是不是要删除的,而不是检查本身,防止最后一个是要删除的(如何根据一个指针删除非最后一个节点的方法,在前面已经说过,但是当这个节点可能是最后一个时,这个方法不再有效)
/**
* 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) {
ListNode* phead = new ListNode(0);
phead->next = head;
ListNode* tmp = phead;
while(tmp->next)
{
if(tmp->next->val == val)
{
ListNode* t = tmp->next;
tmp->next = tmp->next->next;
delete t;
}
else
tmp = tmp->next;
}
return phead->next;
}
};