Easy
去除鏈列中值為val的元素
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Definition for singly-linked list.
class ListNode(object):
def init(self, x):
self.val = x
self.next = None
我寫了下面的遞歸代碼阎姥,但是出現了running time error敲才,說是遞歸深度太大。但是我看論壇里排第一的用的是相同的思路倍啥,不過是用java寫得。這里不是很明白原因饮六。
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if not head:
return None
head.next = self.removeElements(head.next, val)
return head.next if head.val == val else head
下面是另外一位coder的解法冤荆。利用指針操作。
# 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
"""
dummy = ListNode(-1)
dummy.next = head
curr = dummy
while curr.next:
if curr.next.val == val:
curr.next = curr.next.next
else:
curr = curr.next
return dummy.next