题目描述
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
注意点
1、删除点在开头;
2、删除点在结尾;
3、连续删除两个位置;
4、需delete手动释放内存;
头结点命中处理
1、头结点命中特殊处理;
![](https://i-blog.csdnimg.cn/blog_migrate/d23890f14680059da581c54cc7ba9b5f.png)
2、引入虚拟头结点;
![](https://i-blog.csdnimg.cn/blog_migrate/be20a4d4b113557f15c3efa001ca294c.png)
删除操作
1、两个指针完成删除;
![](https://i-blog.csdnimg.cn/blog_migrate/547367978d5c0f03c71feb2ca9eba26c.png)
2、一个指针完成删除;
![](https://i-blog.csdnimg.cn/blog_migrate/f0168927bd066648fcb481013d0d3d1c.png)
方法一
头结点命中特殊处理,利用两个指针完成删除操作;
/**
* 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 head;
ListNode *p = head;
ListNode *pre = p;
while( p )
{
if( p->val == val )
{
if( pre == p )
{
head = head->next;
p = head;
pre = p;
}
else
{
pre->next = p->next;
p = p->next;
}
}
else
{
pre = p;
p = p->next;
}
}
return head;
}
};
方法二
引入虚拟头结点,利用两个指针完成删除操作;
/**
* 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 head;
ListNode *res = new ListNode(0);
ListNode *p = head;
res->next = head;
ListNode *pre = res;
while( p )
{
if( p->val == val )
pre->next = p->next;
else
pre = p;
p = p->next;
}
return res->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) {
if( head == NULL )
return head;
ListNode *res = new ListNode(0);
res->next = head;
ListNode *p = res;
while( p->next )
{
if( p->next->val == val )
{
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp;
}
else
p = p->next;
}
return res->next;
}
};