題目描述:給定一個鍊錶,旋轉鍊錶,使得每個節點向右移動k個位置,其中k是一個非負數
範例:給出鍊錶1-> 2->3->4->5->null和k=2;返回4->5->1->2->3->null
首先,觀察這個題目要達到的目的,其實,換一種說法,可以這樣來描述:給出一個k值,將鍊錶從倒數第k個節點處起之後的部分移動到鍊錶前面,就範例來說,其實是將4->5這一部分移到整個鍊錶前面,變成4->5->1->2->3->null。不過,要注意的是,題中沒有給出k的大小,當k比鍊錶的長度還大的時候,我們就需要先用k對鍊錶的長度求餘,比如,如果k = 7,那麼上面的範例還是將4->5移到整個鍊錶前面。
所以說,這個題的思路可以這樣來總結:
1. 先求出整個鍊錶的長度
2. 根據k值找到需要移動的部分鍊錶的前驅(範例的3)
3. 在前驅之後將鍊錶斷開,移動後半部
程式碼如下:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head: the list # @param k: rotate to the right k places # @return: the list after rotation def rotateRight(self, head, k): if head is None: return head cur = head count = 1 # 计算链表长度 while cur.next: cur = cur.next count += 1 # 为节省代码量,这里是一个很有技巧的处理:用尾节点链接头结点 cur.next = head # 此处,k为cur从尾节点到要断开部分的前驱需走的步数 k = count - k % count # 找到前驱 while k != 0: cur = cur.next k -= 1 # 断开 head = cur.next cur.next = None # 因为首尾已经相连,所以直接返回前驱后面的那个节点即可,此处引用为head return head # write your code here
要注意的是21行首尾相連的技巧,這大大節省了我們的程式碼量,其實,就按之前思路中所描述的一步步來,也沒問題。但是這個技巧確實很棒,值得學習。具體的細節我寫在程式碼註解裡了。
謝謝閱讀,希望能幫助大家,謝謝大家對本站的支持!
更多Python 資料結構之旋轉鍊錶相關文章請關注PHP中文網!

pythonlistscanStoryDatatepe,ArrayModulearRaysStoreOneType,and numpyArraySareSareAraysareSareAraysareSareComputations.1)列出sareversArversAtileButlessMemory-Felide.2)arraymoduleareareMogeMogeNareSaremogeNormogeNoreSoustAta.3)

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

useanArray.ArarayoveralistinpythonwhendeAlingwithHomoGeneData,performance-Caliticalcode,orinterfacingwithccode.1)同質性data:arraysSaveMemorywithTypedElements.2)績效code-performance-calitialcode-calliginal-clitical-clitical-calligation-Critical-Code:Arraysofferferbetterperbetterperperformanceformanceformancefornallancefornalumericalical.3)

不,notalllistoperationsareSupportedByArrays,andviceversa.1)arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,wheremactsperformance.2)listssdonotguaranteeconecontanttanttanttanttanttanttanttanttanttimecomplecomecomplecomecomecomecomecomecomplecomectacccesslectaccesslecrectaccesslerikearraysodo。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

禪工作室 13.0.1
強大的PHP整合開發環境

SublimeText3漢化版
中文版,非常好用

Dreamweaver Mac版
視覺化網頁開發工具