1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第二百零三题
(1)题目
英文:
Remove all elements from a linked list of integers that have value val.
中文:
删除链表中等于给定值 val 的所有节点。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
(2)解法
迭代求解
(耗时:80ms,内存:16.8M)
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
prev = dummy
last = prev.next
while last :
if last.val == val:
prev.next = last.next
last = prev.next
else:
prev = prev.next
last = prev.next
return dummy.next
第二种:
(耗时:72ms,内存:16.6M)
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
while head and head.val == val:
head = head.next
pre, cur = head, head and head.next
while cur:
if cur.val == val:
pre.next = cur = cur.next
else:
pre, cur = cur, cur.next
return head
注意:
1.关键点:当当前的cur的值=val时,就要将之前的pre的指针指向下一个节点cur.next。
② 递归求解
(耗时:92ms,内存:24.5M)
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
if not head: return
head.next = self.removeElements(head.next, val)
return head.next if head.val == val else head
注意:
1.if not head: return
会直接返回空表[]。