很经典的一道题,但波波老师讲出了新的东西。设立虚拟结点,因为每次循环cur->next只有头结点无法考虑,但是你要是单独考虑头结点,万一头结点删除你还需要再考虑下一头结点,就形成了很麻烦的while结构。有了虚拟头结点,问题全都解决了。
/**
* 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* dummyhead;
dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* cur;
cur = dummyhead;
while (cur->next!=NULL)
{
if (cur->next->val == val)
{
ListNode* delNode;
delNode = cur->next;
cur->next = delNode->next;
delete delNode;
}
else
cur = cur->next;
}
return dummyhead->next;
}
};