網站首頁 編程語言 正文
本文實例為大家分享了python實現單鏈表反轉的具體代碼,供大家參考,具體內容如下
代碼如下:
class Node(object):
? ? def __init__(self, elem, next_=None):
? ? ? ? self.elem = elem
? ? ? ? self.next = next_
?
def reverseList(head):
? ? if head == None or head.next==None: ?# 若鏈表為空或者僅一個數就直接返回
? ? ? ? return head?
? ? pre = None
? ? next = None
? ? while(head != None):?
? ? ? ? next = head.next ? ? # 1
? ? ? ? head.next = pre ? ? # 2
? ? ? ? pre = head ? ? ?# 3
? ? ? ? head = next ? ? ?# 4
? ? return pre
if __name__ == '__main__':
? ? l1 = Node(3) ? ?# 建立鏈表3->2->1->9->None
? ? l1.next = Node(2)
? ? l1.next.next = Node(1)
? ? l1.next.next.next = Node(9)
? ? l = reverseList(l1)
? ? print (l.elem, l.next.elem, l.next.next.elem, l.next.next.next.elem)
原始單鏈表:
反轉后單鏈表:
反轉過程如下:
第一步:next = head.next
將 head.next 賦值給 next 變量,即next 指向了節點2,先將節點2 保存起來。
第二步:head.next = pre (初始pre==None)
將 pre 變量賦值給 head.next,即 此時節點1 指向了 None
第三步:pre = head
將 head 賦值給了 pre,即 pre 指向節點1,將節點1 設為“上一個節點”
第四步:head = next
將 next 賦值給 head,即 head 指向了節點2,此時節點2 設為“頭節點”
第一次循環完畢,進入第二次循環,如下圖:
第一步:next = head.next
將 head.next 賦值給 next 變量,即 next 指向了節點3,先將節點3 保存起來。
第二步:head.next = pre (此時的pre已經不為None)
將 pre 賦值給 head.next,pre 在上一次循環的時候指向了節點1,那么這一步的意義就是節點2 指向了 節點1,完成1和2節點的反轉。
第三步:pre = head
將 head 賦值給了 pre,即 pre 指向節點2,將節點2 設為“上一個節點”
第四步:head = next
將 next 賦值給 head,即 head 指向了節點3。此時節點3 設為“頭節點”
第二次循環完畢,以此類推!第三次第四次第五次循環。最后反轉成如下圖
若干注意點:
(1)幫助記憶圖:
(2)當前頭節點的下一個節點一定要保存(比如:當前頭節點為2,先將節點3 保存起來)
(3)實現反轉的key point: head.next = pre
原文鏈接:https://blog.csdn.net/gongliming_/article/details/88712221
相關推薦
- 2023-11-26 XMLHttpRequest的readyState狀態值
- 2023-05-08 C語言超詳細講解雙向帶頭循環鏈表_C 語言
- 2024-01-16 Oracle的取整函數
- 2022-08-06 pandas數據合并之pd.concat()用法詳解_python
- 2022-08-13 SpringSecurity+JWT實現認證及授權詳細步驟
- 2022-11-03 C++高精度算法的使用場景詳解_C 語言
- 2022-06-01 Go中的gRPC入門教程詳解_Golang
- 2022-06-17 mongodb?數據塊的遷移流程分析_MongoDB
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支