当前位置: 首页 > 后端技术 > Python

剑指报价详解(链表)——python

时间:2023-03-26 16:41:37 Python

3.从头到尾打印链表#-*-coding:utf-8-*-#classListNode:#def__init__(self,x):#self.val=x#self.next=Noneclass解决方法:#return列表值从尾到头的顺序,例如[1,2,3]defprintListFromTailToHead(self,listNode):#在这里写代码ifnotlistNode:return[]l=[]whilelistNode:l.append(listNode.val)listNode=listNode.next返回l[::-1]14。链表类最后第k个节点解决方案:defFindKthToTail(self,head,k):#这里写代码ifnotheadork<=0:returnNonep=q=headt=0whilepandt2->3->4->5->NULL输出:5->4->3->2->1->NULL迭代解法:class解法:defreverseList(self,head:ListNode)->ListNode:cur,pre=head,Nonewhilecur:temp=cur.next#保存原链表的后续内容,防止链表断掉。temp是从原链表的第二个节点开始的链表cur.next=pre#将cur的指针直接指向prepre=cur#替换修改后的precur=temp#替换修改后的curreturnpre16.MergeTwo排序链表#classListNode:#def__init__(self,x):#self.val=x#self.next=Noneclass解决方案:#返回合并后的列表defMerge(self,pHead1,pHead2):#如果pHead1在这里写代码==无:如果pHead2则返回pHead2==无:返回pHead1cur=ListNode(0)#而pHead1和pHead2:如果pHead1.val<=pHead2.val:cur=pHead1cur.next=self.Merge(pHead1.next,pHead2)else:cur=pHead2cur.next=self.Merge(pHead1,pHead2.next)返回cur25。复杂链表的递归复制会很简单,但是这个题可能不太适合pythonclass解决方法:#ReturnRandomListNodedefClone(self,pHead):#这里写代码ifnotpHead:returnNonepCopy=RandomListNode(pHead.label)#新建一个与pHead内容相同的RandomListNode对象pCopy.random=pHead.random#一个RandomListNode需要指定random和next的值#pCopy.next=pHead.nextpCopy.next=self.Clone(pHead.next)returnpCopy