203. Remove Linked List Elements
程序员文章站
2024-02-19 08:32:16
...
# 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 not head:
return head
if not head.next:
if head.val == val:
return None
else:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
p = head
while p:
if p.val == val:
pre.next = p.next
p = p.next
else:
pre = p
p = p.next
return dummy.next
有一种很天才的做法,递归法:
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)
if head.val == val:
return head.next
else:
return head
推荐阅读
-
leetcode 203. Remove Linked List Elements
-
LeetCode 203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
Leetcode 203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
【leetcode】203. Remove Linked List Elements
-
LeetCode(52)-Remove Linked List Elements
-
203. Remove Linked List Elements