新聞中心
這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
刷題系列-用遞歸和遍歷兩個(gè)方法反轉(zhuǎn)一個(gè)單鏈隊(duì)列-創(chuàng)新互聯(lián)
二叉樹(shù)的題目告一段落,后面陸續(xù)做了些基礎(chǔ)的題;感覺(jué)沒(méi)有什么好記錄的。

這次是一個(gè)非?;A(chǔ)題目用遞歸和遍歷兩個(gè)方法反轉(zhuǎn)一個(gè)單鏈隊(duì)列。如下所示。
Input:
1->2->3->4->5->NULL
Output:
5->4->3->2->1->NULL
遞歸的方法,考慮了下其實(shí)方法很多,我想了比較簡(jiǎn)單的,就是取出第一個(gè)節(jié)點(diǎn),放在后續(xù)節(jié)隊(duì)列的最后,如此循環(huán)遞歸直到只有一個(gè)節(jié)點(diǎn)位置。代碼是很好寫,就是效率太低,提交運(yùn)行時(shí)間1008ms,實(shí)在是,主要每次一個(gè)節(jié)點(diǎn)排序,都要遍歷整條隊(duì)列,其實(shí)應(yīng)該有更好的。
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head node = self.reverseList(head.next) head.next = None checknode = node while checknode.next != None: checknode = checknode.next checknode.next = head return node
遍歷方法也很簡(jiǎn)單,就是新建一個(gè)隊(duì)列做棧,把單鏈隊(duì)列的按照順序放入,然后反向推出節(jié)點(diǎn),重組隊(duì)列返回即可。提交運(yùn)行時(shí)間34ms, 效率高很多。
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if head == None: return head nodeStack = [] while head != None: nodeStack.append(head) head = head.next print(len(nodeStack)) newHead = nodeStack.pop() point = newHead while nodeStack != []: point.next = nodeStack.pop() point = point.next point.next = None return newHead
網(wǎng)站名稱:刷題系列-用遞歸和遍歷兩個(gè)方法反轉(zhuǎn)一個(gè)單鏈隊(duì)列-創(chuàng)新互聯(lián)
標(biāo)題路徑:http://www.dlmjj.cn/article/peggo.html


咨詢
建站咨詢
