今天连续做了三道题, 感觉越来越有感觉, 第三题直接行云流水, 10 min AC
目录203.移除链表元素 单链表巧用dummy_head删除
一开始犯的一个逻辑错误: val的节点可能连续出现
while cur and cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
cur = cur.next # 这一行错误, 应当加上else
解题思路
-
使用dummy_head:
-
可以把目光仅聚焦在类似
递推
的关系上 -
但是需要注意: 若返回
head
, 必须返回dummy_head.next
-
-
不使用dummy_head:
-
需要用循环排除头结点是否满足删除条件
-
同时需要注意当前节点可能是
None
, 循环条件是while cur and cur.next!=None:
-
代码
使用dummy_head
# 使用dummy_head
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy_head = ListNode(next=head)
cur = dummy_head
while cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy_head.next
不使用dummy_head
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
cur = head
# 如果头几个node就是val
while cur and cur.val == val:
cur = cur.next
head = cur
# 查询与删除
while cur and cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head
707. 设计链表 找目标位置的前一个node
解题思路
注意对于index的delete和add, 都是找到其目标位置index前一个node
代码
class Node:
def __init__(self, val: int, next = None):
self.val = val
self.next = None
class MyLinkedList:
# 一个带有dummy_head的单链表
def __init__(self):
self.head = Node(0)
self.count = 0
def get(self, index: int) -> int:
if index >= self.count:
return -1
# 根据题意: index=0表示第0个
cur = self.head.next
for i in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
obj = Node(val)
obj.next = self.head.next
self.head.next = obj
self.count += 1
def addAtTail(self, val: int) -> None:
# 先找到末尾
cur = self.head
while cur.next != None:
cur = cur.next
# 再加入
obj = Node(val)
cur.next = obj
self.count += 1
def addAtIndex(self, index: int, val: int) -> None:
if index > self.count:
return -1
# 找到index前一个
cur = self.head
for i in range(index):
cur = cur.next
# 加入
obj = Node(val)
obj.next = cur.next
cur.next = obj
self.count += 1
def deleteAtIndex(self, index: int) -> None:
if index >= self.count:
return
# 找到要删的前一个
cur = self.head
for i in range(index):
cur = cur.next
# 删除
cur.next = cur.next.next
self.count -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
206. 反转链表
Reverse考虑0/1的Corner Case, 存储3个指针
解题思路
Reverse
- 考虑0/1的Corner Case
- 存储3个指针: 一前, 一后, 以及后面节点的next值
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
i = head
# corner case: 数量为0或者1, 无需reverse
if i and i.next:
j = i.next
else:
return head
# 原来的head, 现在的tail, next设为None
i.next = None
# 遍历: 记得保存j.next
while j != None:
t = j.next
j.next = i
i = j
j = t
# 最后i为head
head = i
return head
标签:Case,index,head,cur,val,self,next,链表,移除
From: https://www.cnblogs.com/ywh-pku/p/16837765.html