海外推廣工作怎么樣seo排名推廣
NC50 鏈表中的節(jié)點(diǎn)每k個(gè)一組翻轉(zhuǎn)
題目:
思路:
這種題目比較習(xí)慣現(xiàn)在草稿本涂涂畫(huà)畫(huà)鏈表處理過(guò)程。整體思路是賦值新的鏈表,用游離指針遍歷原始鏈表進(jìn)行翻轉(zhuǎn)操作,當(dāng)游離個(gè)數(shù)等于k時(shí),就將翻轉(zhuǎn)后的鏈表接到新的鏈表后,如最后個(gè)數(shù)不滿(mǎn)k,則將原始鏈表剩余節(jié)點(diǎn)接到新的鏈表后。
游離的過(guò)程中,每次將當(dāng)前游離的頭節(jié)點(diǎn)賦為最新遍歷的節(jié)點(diǎn),同時(shí)將前一個(gè)節(jié)點(diǎn)鏈接到下一個(gè)節(jié)點(diǎn)。
這個(gè)代碼寫(xiě)的過(guò)程中有點(diǎn)繞,過(guò)程有些bug,寫(xiě)了個(gè)打印鏈表的函數(shù)調(diào)試了下。
代碼
class Solution:def reverseKGroup(self , head: ListNode, k: int) -> ListNode:def printList(h):## 打印鏈表result = []t = hwhile t:result.append(t.val)t = t.nextprint(result)# write code hereif not head or not head.next or k == 1:return headnewHead = ListNode(head.val) ## 最終輸出的頭節(jié)點(diǎn)newTail = ListNode(head.val) ## 每次翻轉(zhuǎn)完成確定尾節(jié)點(diǎn)curHead = ListNode(head.val) ## 當(dāng)前游離的頭節(jié)點(diǎn)curNode = curHead ## 當(dāng)前游離節(jié)點(diǎn)curTail = curHeadoriNextNode = head.next ## 原始節(jié)點(diǎn)順序oriCurHead = head ## 記錄原始鏈表中每次遍歷的組里的頭節(jié)點(diǎn)count = 1switchTime = 0 ## 成功翻轉(zhuǎn)的組數(shù)while curNode:# print(f'{switchTime}次交換的{count}位')if count < k and oriNextNode:## 可以繼續(xù)遍歷的情況curNode = ListNode(oriNextNode.val) ## 游離原始鏈表的節(jié)點(diǎn)curNode.next = curHead ## 將最新的節(jié)點(diǎn)指向當(dāng)前游離組里的頭節(jié)點(diǎn),實(shí)現(xiàn)翻轉(zhuǎn)curHead = curNode ## 最新節(jié)點(diǎn)為頭節(jié)點(diǎn)oriNextNode = oriNextNode.next if oriNextNode else None ## 繼續(xù)遍歷原始鏈表count+=1elif count == k:## 成功翻轉(zhuǎn)的情況count = 1switchTime += 1if switchTime == 1:newHead = curHead ## 第一次翻轉(zhuǎn),獲取翻轉(zhuǎn)后的頭節(jié)點(diǎn)newTail = curTailelse:newTail.next = curHead ## 除了第一次翻轉(zhuǎn),其余均用翻轉(zhuǎn)后的尾節(jié)點(diǎn)做關(guān)聯(lián)指向下一組節(jié)點(diǎn)newTail = curTailcurHead = ListNode(oriNextNode.val) if oriNextNode else None ## 獲取下一組的頭節(jié)點(diǎn)curNode = curHeadcurTail = curHeadoriCurHead = oriNextNode ## 獲取下一組的原始頭節(jié)點(diǎn)oriNextNode = oriNextNode.next if oriNextNode else Noneelif switchTime >= 1:## 無(wú)法繼續(xù)遍歷,且有翻轉(zhuǎn)過(guò)的情況newTail.next = oriCurHeadreturn newHeadelse:## 一次翻轉(zhuǎn)都未成功的情況return head# printList(newHead)# printList(curHead)# printList(head) return newHead