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