题目:
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
解释:
删除val为指定值的结点。
注意head结点需要特殊处理一下。
python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return None
while head.val==val:
head=head.next
if not head:
return None
tmp=head
while tmp and tmp.next:
if tmp.next.val==val:
tmp.next=tmp.next.next
else:
tmp=tmp.next
return head
c++代码:
/**
* 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;
while(head->val==val)
{
head=head->next;
if(!head)
return NULL;
}
ListNode* tmp=head;
while(tmp && tmp->next)
{
if (tmp->next->val==val)
tmp->next=tmp->next->next;
else
tmp=tmp->next;
}
return head;
}
};
总结:
对于这种删除元素的题目,一定要特殊考虑一下head
,以及在确保head->next
完全没有问题的时候再更新tmp
。