题目描述:
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hide Tags Linked List
方案二:
直接一次遍历参数链表,将值不等于目标值的节点取出来,依次放入一个新链表中。
方案三:前面两种方案的优化
利用双指针,能减少删除次数,尤其是对于存在连续的目标值节点的链表能提高很大的效率。
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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Hide Tags Linked List
分析:要删除指定值的链表节点,有三种种可行的方案:
方案二:
直接一次遍历参数链表,将值不等于目标值的节点取出来,依次放入一个新链表中。
方案三:前面两种方案的优化
利用双指针,能减少删除次数,尤其是对于存在连续的目标值节点的链表能提高很大的效率。
以下是实现的C++代码:
/*方案一///42ms/*/
/**
* 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* tmp = head;
while(tmp != NULL && tmp->val == val) //找到第一个值不为val的节点。
{
tmp = tmp->next;
}
head = tmp; //删除头部连续为val的所有节点。
while(tmp != NULL && tmp->next != NULL)
{
if(tmp->next->val == val) //删除值为val的节点
{
tmp->next = tmp->next->next;
}
else
tmp = tmp->next;
}
return head;
}
};
/*方案二///38ms//*/
/**
* 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* tmp = head;
while(tmp != NULL && tmp->val == val)
{
tmp = tmp->next;
}
if(tmp == NULL) //表示参数链表中全是目标值
return NULL;
ListNode* nhead = new ListNode(tmp->val); //新链表的头节点
ListNode* ntmp = nhead;
tmp = tmp->next;
while(tmp != NULL) //将所有非目标值的节点条件到新链表中
{
if(tmp->val != val)
{
ListNode* t = new ListNode(tmp->val);
ntmp->next = t;
ntmp = ntmp->next;
}
tmp = tmp->next;
}
return nhead;
}
};
/*//方案三/36ms//
/**
* 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* tmp = head;
while(tmp != NULL && tmp->val == val) //找到第一个值不为val的节点。
{
tmp = tmp->next;
}
if(tmp == NULL)
return NULL;
head = tmp; //删除头部连续为val的所有节点。
ListNode* t1 = head;
ListNode* t2 = head->next;
while(t1 != NULL && t2 != NULL)
{
if(t2->val != val) //删除值为val的节点
{
t1->next = t2;
t1 = t2;
t2 = t2->next;
}
else
t2 = t2->next;
}
if(t1->next != NULL && t1->next->val == val)
t1->next = NULL;
return head;
}
};
但是,当链表中不含有目标值时,方案一和方案三是一样的,方案二反而效率较低。