删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->val=-1;
p->next=head;
struct ListNode* res=p;
struct ListNode* q=head;
while(q)
{
if(q->val==val)
{
p->next=q->next;
q=p->next;
}
else
{
p=q;
q=q->next;
}
}
return res->next;
}
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)
{
ListNode* p=new ListNode(-1);
p->next=head;
ListNode* q=head;
ListNode* res=p;
while(q)
{
if(q->val==val)
{
p->next=q->next;
q=p->next;
}
else
{
p=q;
q=q->next;
}
}
return res->next;
}
};
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
"""
p=ListNode(-1)
p.next=head
res=p
q=head
while q:
if q.val==val:
p.next=q.next
q=p.next
else:
p=q
q=q.next
return res.next