Python數(shù)據(jù)結(jié)構(gòu)之翻轉(zhuǎn)鏈表
翻轉(zhuǎn)一個鏈表
樣例:給出一個鏈表1->2->3->null,這個翻轉(zhuǎn)后的鏈表為3->2->1->null
一種比較簡單的方法是用“摘除法”。就是先新建一個空節(jié)點(diǎn),然后遍歷整個鏈表,依次令遍歷到的節(jié)點(diǎn)指向新建鏈表的頭節(jié)點(diǎn)。
那樣例來說,步驟是這樣的:
1. 新建空節(jié)點(diǎn):None
2. 1->None
3. 2->1->None
4. 3->2->1->None
代碼就非常簡單了:
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the reversed linked list. Reverse it in-place. """ def reverse(self, head): temp = None while head: cur = head.next head.next = temp temp = head head = cur return temp # write your code here
當(dāng)然,還有一種稍微難度大一點(diǎn)的解法。我們可以對鏈表中節(jié)點(diǎn)依次摘鏈和鏈接的方法寫出原地翻轉(zhuǎn)的代碼:
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the reversed linked list. Reverse it in-place. """ def reverse(self, head): if head is None: return head dummy = ListNode(-1) dummy.next = head pre, cur = head, head.next while cur: temp = cur # 把摘鏈的地方連起來 pre.next = cur.next cur = pre.next temp.next = dummy.next dummy.next = temp return dummy.next # write your code here
需要注意的是,做摘鏈的時候,不要忘了把摘除的地方再連起來
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- python算法題 鏈表反轉(zhuǎn)詳解
- 單鏈表反轉(zhuǎn)python實現(xiàn)代碼示例
- Python二叉搜索樹與雙向鏈表轉(zhuǎn)換實現(xiàn)方法
- Python實現(xiàn)鏈表反轉(zhuǎn)的方法分析【迭代法與遞歸法】
- python實現(xiàn)反轉(zhuǎn)部分單向鏈表
- Python3實現(xiàn)的反轉(zhuǎn)單鏈表算法示例
- Python 數(shù)據(jù)結(jié)構(gòu)之旋轉(zhuǎn)鏈表
- Python二叉搜索樹與雙向鏈表轉(zhuǎn)換算法示例
- python如何實現(xiàn)單鏈表的反轉(zhuǎn)
- python遞歸實現(xiàn)鏈表快速倒轉(zhuǎn)
相關(guān)文章
python每次處理固定個數(shù)的字符的方法總結(jié)
使用python每次處理固定個數(shù)的字符,很多情況下都會遇到。本文對可能的方法做下總結(jié),供各位朋友學(xué)習(xí)參考2013-01-01python3反轉(zhuǎn)字符串的3種方法(小結(jié))
這篇文章主要介紹了python3反轉(zhuǎn)字符串的3種方法(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11python3的UnicodeDecodeError解決方法
這篇文章主要介紹了python3的UnicodeDecodeError解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12一篇文章教你掌握python數(shù)據(jù)類型的底層實現(xiàn)
這篇文章主要介紹了Python 數(shù)據(jù)類型的底層實現(xiàn)原理分析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-09-09Linux下Python安裝完成后使用pip命令的詳細(xì)教程
這篇文章主要介紹了Linux下Python安裝完成后使用pip命令的詳細(xì)教程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11tensorflow1.15與numpy、keras以及Python兼容版本對照方式
這篇文章主要介紹了tensorflow1.15與numpy、keras以及Python兼容版本對照方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03python線程池 ThreadPoolExecutor 的用法示例
這篇文章主要介紹了python線程池 ThreadPoolExecutor 的用法示例,幫助大家更好得理解和使用python線程池,感興趣的朋友可以了解下2020-10-10