原题
删除链表中等于给定值val的所有节点。
样例
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
解题思路
- 最基础的链表操作,由于第一个节点可能被删除,所以借助Dummy Node
完整代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head is None:
return head
dummy = ListNode(0)
dummy.next = head
current = dummy
while current.next != None:
if current.next.val == val:
current.next = current.next.next
else:
current = current.next
return dummy.next