题目描述:
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
--------------------------------------------------------------------------------------------------------------------------------
本题需要注意的地方在于,由于没有哑节点的存在,因此删除的时候需要判断是不是头结点,头结点的删除和其他节点的删除情况不同。并且题目中指出需要删除所有值为val的节点,因此当所有的值都是等于头结点的值得时候,就需要一直判断头结点。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(head == NULL)
return NULL;
while(head != NULL && head->val == val) //由于不存在哑节点,删除头结点需要特殊判断
{
ListNode *temp = head;
head = temp->next;
delete temp;
}
if(head == NULL)
return NULL;
ListNode *pre = head; //找到值等于val的节点的前一个节点
while(pre->next != NULL)
{
if(pre->next->val == val)
{
ListNode *temp;
temp = pre->next;
pre->next = temp->next;
delete temp;
}
else
pre = pre->next;
}
return head;
}
};