问题
思路
注意头结点的情形。
代码
/**
* 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) return NULL;
ListNode* ret = head;
ListNode* pre = NULL;
while( head ){
if(head->val == val)
{
if(pre)
{
pre->next = head->next;
delete head;
head = pre->next;
}
else
{
ListNode* nex = head->next;
delete head;
head = nex;
ret = head;
}
}
else
{
pre = head;
head = head->next;
}
}
return ret;
}
};
代码1
/**
* 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) return NULL;
ListNode* pre = NULL;
ListNode* p = head;
while(p){
if(p->val == val){
if(!pre){
ListNode* nex = p->next;
delete p;
p = nex;
head = p; // 删除头结点别忘了更新头指针,否则head是垂悬指针
}
else{
pre->next = p->next;
delete p;
p = pre->next;
}
}
else{
pre = p;
p = p->next;
}
}
return head;
}
};