刷题系列 - 用递归和遍历两个方法反转一个单链队列
二叉树的题目告一段落,后面陆续做了些基础的题;感觉没有什么好记录的。
这次是一个非常基础题目用递归和遍历两个方法反转一个单链队列。如下所示。
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
递归的方法,考虑了下其实方法很多,我想了比较简单的,就是取出第一个节点,放在后续节队列的最后,如此循环递归直到只有一个节点位置。代码是很好写,就是效率太低,提交运行时间1008ms,实在是,主要每次一个节点排序,都要遍历整条队列,其实应该有更好的。
#Definitionforsingly-linkedlist.#classListNode:#def__init__(self,x):#self.val=x#self.next=NoneclassSolution:defreverseList(self,head:ListNode)->ListNode:ifhead==Noneorhead.next==None:returnheadnode=self.reverseList(head.next)head.next=Nonechecknode=nodewhilechecknode.next!=None:checknode=checknode.nextchecknode.next=headreturnnode
遍历方法也很简单,就是新建一个队列做栈,把单链队列的按照顺序放入,然后反向推出节点,重组队列返回即可。提交运行时间34ms, 效率高很多。
#Definitionforsingly-linkedlist.#classListNode:#def__init__(self,x):#self.val=x#self.next=NoneclassSolution:defreverseList(self,head:ListNode)->ListNode:ifhead==None:returnheadnodeStack=[]whilehead!=None:nodeStack.append(head)head=head.nextprint(len(nodeStack))newHead=nodeStack.pop()point=newHeadwhilenodeStack!=[]:point.next=nodeStack.pop()point=point.nextpoint.next=NonereturnnewHead
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。