思路:定义虚拟头节点,不用再另外拿出来考虑,返回时也是直接返回虚拟头节点的下一个节点,而不是虚拟头节点。循环链表找到指定值为val的节点后删除该节点,否则继续寻找。
代码:
def removeElements(self, head, val):
# 虚拟节点
dummy_head = ListNode(None, head) # 构造虚拟节点
cur = dummy_head # 设当前访问的节点
while cur.next: # 遍历链表
if cur.next.val == val:
cur.next = cur.next.next # 找到目标节点,并将其删除
else:
cur = cur.next # 未找到,遍历下一个
return dummy_head.next
要点:题比较全,涉及增删改查,没掌握(水淋鸭背),改天补上。。。先贴个代码吧
class MyLinkedList:
def __init__(self):
self.dummy_head = ListNode()
self.size = 0
def get(self, index: int):
if index < 0 or index >= self.size:
return -1
current = self.dummy_head.next
for i in range(index):
current = current.next
return current.val
def addAtHead(self, val: int) -> None:
self.dummy_head.next = ListNode(val, self.dummy_head.next)
self.size += 1
def addAtTail(self, val: int) -> None:
current = self.dummy_head
while current.next:
current = current.next
current.next = ListNode(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
current = self.dummy_head
for i in range(index):
current = current.next
current.next = self.ListNode(val, current.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
current = self.dummy_head
for i in range(index):
current = current.next
current.next = current.next.next
self.size -= 1
思路:
1、双指针:初始化pre,cur,它们分别指定null和头节点,tmp指向头节点next。tmp指向cur.next,cur.next指定pre,pre移动到->cur移动到->tmp,当cur为空返回pre
代码①双指针
def reverseList(self, head):
# 双指针
cur, pre = head, None # 初始化pre,cur,它们分别指定null和头节点
while cur:
tmp = cur.next # cur.next暂存后续节点
cur.next = pre # 修改 next引用指向
pre = cur # 暂存当前节点
cur = tmp # 访问下一个
return pre
2、递归:先写终止条件:如果head为空或者head.next为空,返回head。新头节点pre 指定尾结点,进入递归,一直到尾结点才返回。每一层递归中的head会让下一个节点指向自己,head.next.next=head。然后head自己指向空,达到反转目地。
②递归
def reverseList(self, head):
# 递归 终止条件
if head is None or head.next is None:
return head
pre = self.reverseList(head.next)
head.next.next = head
head.next = None # head.next为空
return pre