题目:
代码:
/**
* 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 *p = head, *pre_p = head;;
while (p != NULL)
{
if (p->val == val){
if (p == head) //指针p与head在同一节点上,由于该节点要销毁,则head需后移
{
head = head->next;
//delete p;
//p = head;
}
if (pre_p == p) //pre_p与p也指向同一节点
{
delete p;
pre_p = p =head;
}
else{ //pre_p指向p的前一节点
pre_p->next = p->next;
delete p;
p = pre_p->next;
}
}
else
{
if (pre_p = p){
p = p->next;
}
else
{
pre_p = p;
p = p->next;
}
}
}
return head;
}
};
运行结果:
Accepted 32ms
代码图例分析: