Python數(shù)據(jù)結(jié)構(gòu)之翻轉(zhuǎn)鏈表
翻轉(zhuǎn)一個鏈表
樣例:給出一個鏈表1->2->3->null,這個翻轉(zhuǎn)后的鏈表為3->2->1->null
一種比較簡單的方法是用“摘除法”。就是先新建一個空節(jié)點,然后遍歷整個鏈表,依次令遍歷到的節(jié)點指向新建鏈表的頭節(jié)點。
那樣例來說,步驟是這樣的:
1. 新建空節(jié)點: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)然,還有一種稍微難度大一點的解法。我們可以對鏈表中節(jié)點依次摘鏈和鏈接的方法寫出原地翻轉(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)文章
和孩子一起學(xué)習(xí)python之變量命名規(guī)則
這篇文章我們給大家總結(jié)了關(guān)于兒童學(xué)習(xí)python中的變量命名規(guī)則相關(guān)知識點內(nèi)容,有興趣的朋友跟著參考學(xué)習(xí)下。2018-05-05
PyCharm利用pydevd-pycharm實現(xiàn)Python遠(yuǎn)程調(diào)試的詳細(xì)過程
這篇文章主要介紹了PyCharm利用pydevd-pycharm實現(xiàn)Python遠(yuǎn)程調(diào)試,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-09-09
全CPU并行處理Pandas操作Pandarallel更快處理數(shù)據(jù)
我們在處理數(shù)據(jù)時,通常小的數(shù)據(jù)對處理速度不敏感,但數(shù)據(jù)量一大,頓時會感覺數(shù)據(jù)處理效率不盡如人意,今天介紹的pandarallel就是一個簡單高效的Pandas并行工具,幾行代碼就可以提高數(shù)據(jù)處理效率,2024-01-01
python使用requests模塊實現(xiàn)爬取電影天堂最新電影信息
這篇文章主要介紹了python使用requests模塊實現(xiàn)爬取電影天堂最新電影信息,本文通過實例代碼給大家介紹了str/list/tuple三者之間怎么相互轉(zhuǎn)換,需要的朋友可以參考下2019-04-04
對Tensorflow中tensorboard日志的生成與顯示詳解
今天小編就為大家分享一篇對Tensorflow中tensorboard日志的生成與顯示詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
python標(biāo)準(zhǔn)算法實現(xiàn)數(shù)組全排列的方法
這篇文章主要介紹了python標(biāo)準(zhǔn)算法實現(xiàn)數(shù)組全排列的方法,實例分析了全排列的原理與Python實現(xiàn)技巧,需要的朋友可以參考下2015-03-03

