網(wǎng)站首頁 編程語言 正文
給定一個單鏈表,將其反轉。其實很容易想到,只需要修改每個結點的指針指向:即令后一個結點指向前一個結點,并且將表頭指針指向最后一個結點即可。
這個過程可以用循環(huán)實現(xiàn),也可以用遞歸來實現(xiàn)。
1、用循環(huán)來實現(xiàn):
class LNode:
? ? def __init__(self, elem):
? ? ? ? self.elem = elem
? ? ? ? self.pnext = None
?
def reverse(head):
? ? if head is None or head.pnext is None: #如果輸入的鏈表是空或者只有一個結點,直接返回當前結點
? ? ? ? return head
? ? pre = None #用來指向上一個結點
? ? cur = newhead = head #cur是當前的結點。newhead指向當前新的頭結點
? ? while cur:
? ? ? ? newhead = cur
? ? ? ? temp = cur.pnext
? ? ? ? cur.pnext = pre #將當前的結點的指針指向前一個結點
? ? ? ? pre = cur
? ? ? ? cur = temp
? ? return newhead
?
if __name__=="__main__":
? ? head = LNode(1)
? ? p1 = LNode(2)
? ? p2 = LNode(3)
? ? head.pnext = p1
? ? p1.pnext = p2
? ? p = reverse(head)
? ? while p:
? ? ? ? print(p.elem)
? ? ? ? p = p.pnext
2、用遞歸來實現(xiàn):
class LNode:
? ? def __init__(self, elem):
? ? ? ? self.elem = elem
? ? ? ? self.pnext = None
?
def reverse(head):
? ? if not head or not head.pnext:
? ? ? ? return head
? ? else:
? ? ? ? newhead = reverse(head.pnext)
? ? ? ? head.pnext.pnext = head #令下一個結點的指針指向當前結點
? ? ? ? head.pnext = None #斷開當前結點與下一個結點之間的指針指向聯(lián)系,令其指向空
? ? ? ? return newhead
?
?
if __name__=="__main__":
? ? head = LNode(1)
? ? p1 = LNode(2)
? ? p2 = LNode(3)
? ? head.pnext = p1
? ? p1.pnext = p2
? ? p = reverse(head)
? ? while p:
? ? ? ? print(p.elem)
? ? ? ? p = p.pnext
以下是圖解遞歸的詳細過程:
原文鏈接:https://blog.csdn.net/qq_34840129/article/details/80776363
相關推薦
- 2023-01-28 Python多線程與同步機制淺析_python
- 2023-08-13 element表單組件的trigger表單驗證邏輯規(guī)則
- 2022-05-24 ASP.NET?MVC使用異步TPL模式_實用技巧
- 2022-11-21 小白也能看懂的Redis遍歷鍵和數(shù)據(jù)庫管理詳解_Redis
- 2022-12-12 python中的線程池threadpool_python
- 2022-05-14 jQuery操作CSS樣式_jquery
- 2022-04-14 zsh: command not found:快速的解決方法
- 2022-06-29 Qt?Design?Studio創(chuàng)建工程的實現(xiàn)方法_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支