写在前面
本人因准备秋招,决定从2024.6.5日起开始正式刷题。之前虽然也陆续刷过,但总是比较零散(力扣Top100只刷了30道),这次真的拖不起了,所以开此贴,请大家监督我。
本贴主要以记录刷题思路为主,不能直接运行,是一种不太标准的伪代码。我用python编程。
6.7完成情况(DAY3)
第一题能把思路写出来,但有非常多的细节问题,还是要抠细节啊。第二题比较系统,需要对着官方代码看,排查细节,而且边界条件真的太狗了!!!第三题过程不复杂,就是细节比较多,而且一环套一环,这次终于算是弄明白咋回事了。
移除链表元素203
虚拟头节点
dummy= ListNode() #注意不是dummy.head=ListNode()
dummy.next=head
current = dummy #容易忘了,开始有个指针
while current.next!=None:
if current.next.val == val: #注意current.next只代表下一个位置,不是对应值
current.next=current.next.next #下一个指针移动到下下个未知
else:
current = current.next #指针移动到下一个位置
return dummy.next
设计链表707
虚拟头节点
#链表类标准写法,要记住
class ListNode:
def __init__(self,val=0,next=None):
self.val=val
self.next=next
class MyLinkList:
def __init__(self):
self.size=0 #初始化计数器
self.head=ListNode(0)#虚拟了一个头节点0
def get(self,index):
if index<0 or index >= self.size: #不是size-1,考虑一下极端情况
return -1
cur = self.head # 第0个数前一个位置
while index: #如果等于0,不运行
cur = cur.next, index-=1
return cur.next.val
def addAthead(self,val):
newnode=ListNode(val) #以val为头节点新建链表
newnode.next = self.head.next #新链表链接到当前头节点
self.head.next = newnode #原链表连接到新链表头节点
self.size += 1
# return self.head.next #原题输出是None
def addAtTail(self, val):
cur = self.head
while cur.next:
cur = cur.next
cur.next = ListNode(val)
self.size += 1
# return self.head.next
def addAtIndex(self, index, val):
if index<0 or index > self.size: #这里是大于,因为比如只有一个元素,size=1,index可以在0或1处插入新值
return #这里没必要return -1
cur = self.head
while index:
cur = cur.next, index -= 1
newnode = ListNode(val)
newnode.next = cur.next
cur.next = newnode
self.size += 1
# return self.head.next
def deleteAtIndex(self, index):
if index<0 or index >= self.size: #这里是大于等于,因为比如只有一个元素,size=1,index只能取0不能取1
return
cur = self.head
while index:
cur = cur.next, index -= 1
cur.next = cur.next.next
self.size -= 1
反转链表206
双指针法
pre, cur = None, head
while cur!=None:
tmp = cur.next #趁cur原始链接没断,先把cur下一位用tmp保存下来,不然一会儿找不到
cur.next = pre
pre = cur #pre下一位去找cur
cur = tmp #cur下一位去找tmp
return pre
递归法(函数需要加self.保持全局可调用)
def reverse(pre, cur):
if cur == None: return pre
tmp = cur.next
cur.next = pre
return reverse(cur, tmp)
def reverselist(head):
return reverse(None,pre)