删除链表中等于给定值val
的所有节点。
样例
给出链表 1->2->3->3->4->5->3
, 和 val = 3
, 你需要返回删除3之后的链表:1->2->4->5
。
python:
"""
Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
"""
class Solution:
"""
@param: head: a ListNode
@param: val: An integer
@return: a ListNode
"""
def removeElements(self, head, val):
# write your code here
dummy = ListNode(-1)
dummy.next = head
cur = head
pre = dummy
while cur:
if cur.val == val:
pre.next = cur.next
else:
pre = pre.next
cur = cur.next
return dummy.next
C++:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*
* @param head: a ListNode
* @param val: An integer
* @return: a ListNode
*/
ListNode * removeElements(ListNode * head, int val) {
// write your code here
ListNode *pre = NULL;
ListNode *cur = head;
ListNode *buf;
while (cur != NULL)
{
if(cur->val == val)
{
if (pre == NULL)
head = cur->next;
else
pre->next = cur->next;
buf = cur;
cur = cur->next;
delete buf;
}
else
{
pre = cur;
cur = cur->next;
}
}
return head;
}
};