2024.5.11-2024.5.15
移除链表元素
#判断头节点是否空,#并且头节点为要删除的值,头节点向后移while head and head.val==val:head=head.nextif not head: returncur=head#当前指针指向的下一个元素为val,当前指针指向下一个的下一个#否则,当前指针向后移动一位while cur.next:if cur.next.val==val:cur.next=cur.next.nextelse:cur=cur.nextreturn head
设计链表
class ListNode:def __init__(self,val):self.val=valself.next=Noneclass MyLinkedList(object):def __init__(self):self.size=0self.head=ListNode(0)def get(self, index):""":type index: int:rtype: int"""if index<0 or index>=self.size:return -1cur=self.headfor i in range(index+1):cur=cur.nextreturn cur.valdef addAtHead(self, val):""":type val: int:rtype: None"""#这个是实现从头部节点加入数据的代码部分# p=ListNode(val)# p.next=self.head.next# self.head.next=p# self.size+=1#这个是调用类内已经写好的addAtIndex函数self.addAtIndex(0,val)def addAtTail(self, val):""":type val: int:rtype: None"""#这个是实现从尾部节点加入数据的代码部分# cur=self.head# p=ListNode(val)# p.next=None# for i in range(self.size):# cur=cur.next# cur.next=p# self.size+=1#这个是调用类内已经写好的addAtIndex函数self.addAtIndex(self.size,val)def addAtIndex(self, index, val):""":type index: int:type val: int:rtype: None"""if index<0 or index>self.size:return -1cur=self.headfor i in range(index):cur=cur.nextp=ListNode(val)p.next=cur.nextcur.next=pself.size+=1def deleteAtIndex(self, index):""":type index: int:rtype: None"""if index<0 or index>=self.size:return -1cur=self.headfor i in range(index):cur=cur.nextcur.next=cur.next.nextself.size-=1
反转链表
自己实现的
pre=Nonecur=headif cur==None: return headtmp=cur.nextwhile tmp:cur.next=prepre=curcur=tmptmp=tmp.nextcur.next=prereturn cur
参照代码随想录更改的
pre=Nonecur=headwhile cur:tmp=cur.nextcur.next=prepre=curcur=tmpreturn pre
两两交换链表中的节点
我的垃圾代码,拼拼凑凑
dummy_head = ListNode(next = head)pre=dummy_headif dummy_head.next==None: return headcur=pre.nextbeh=cur.nextwhile beh:tmp=beh.nextpre.next=behbeh.next=curcur.next=tmppre=curcur=tmpif tmp!=None:beh=tmp.nextelse:beh=Nonereturn dummy_head.next
删除链表中的倒数第N个节点
dummy=ListNode(next=head)slow=dummyfast=dummyfor i in range(n):fast=fast.nextwhile fast.next:fast=fast.nextslow=slow.nextslow.next=slow.next.nextreturn dummy.next
链表相交
p1,p2=headA,headBAsize,Bsize=0,0while p1:p1=p1.nextAsize+=1while p2:p2=p2.nextBsize+=1if Asize-Bsize>=0:p1,p2=headB,headAAsize,Bsize=Bsize,Asizeelse:p1,p2=headA,headBfor _ in range(Bsize-Asize):p2=p2.nextwhile p1:if p1==p2:return p1p1=p1.nextp2=p2.nextreturn None
环形链表II
fast,slow=head,headwhile fast and fast.next:fast=fast.next.nextslow=slow.nextif slow==fast:x1=headx2=slowwhile x1!=x2:x1=x1.nextx2=x2.nextreturn x1