網站首頁 編程語言 正文
本文實例為大家分享了Python實現環形鏈表的具體代碼,供大家參考,具體內容如下
我們將單向鏈表的最后一個節點的指針指向鏈表的頭部(第一個節點),那么就形成了一個環形鏈表。環形節點可以從任意節點開始遍歷其他的節點。
這里主要實現了環形鏈表節點的遍歷、添加、插入、刪除,反轉。
代碼如下:
class Player:
? ? """節點類"""
? ? def __init__(self):
? ? ? ? """初始化姓名,分數,指針"""
? ? ? ? self.name = ''
? ? ? ? self.score = 0
? ? ? ? self.next = None
?
?
def ergodic(head, num=None, is_print=False):
? ? """遍歷函數,num是遍歷到哪一個位置序號,is_print是否觸發打印方法"""
? ? if head.next is None:
? ? ? ? return None
? ? ptr = head
? ? count = 0
? ? while True:
? ? ? ? count += 1
? ? ? ? if is_print:
? ? ? ? ? ? print('No.'+str(count), ptr.name, ptr.score, '--->', ptr.next.name)
? ? ? ? if count == num:
? ? ? ? ? ? break
? ? ? ? if ptr.next == head:
? ? ? ? ? ? break
? ? ? ? ptr = ptr.next
? ? return ptr ?# 返回遍歷完成后的最后一個節點
?
?
def invert(x): ?# x是鏈表的第一個節點
? ? """反轉環形鏈表"""
? ? y = x.next ?# y是x原來的next
? ? x.next = ergodic(x) ?# 將第一個節點的next指向最后一個節點(因為反轉了)
? ? while True: ?# 循環反轉后面的所有節點
? ? ? ? r = y.next
? ? ? ? y.next = x
? ? ? ? if r == head: ?# r是head說明y已經是原本鏈表的最后一個節點了
? ? ? ? ? ? return y ?# 返回y,這個y是反轉后的鏈表的第一個節點
? ? ? ? x = y
? ? ? ? y = r
?
?
head = Player()
ptr = head
?
?
while True:
? ? select = input("(1).新增 ? (2).查看 ? (3).插入 ? (4).刪除 ? (5).反轉 ? (6).離開\n輸入:")
? ? if select == "1": ?# 新增節點
? ? ? ? ptr = ergodic(head) ?# 獲取當前鏈表最后一個節點
? ? ? ? if ptr is None: ?# ptr為None說明當前在添加第一個節點head
? ? ? ? ? ? head.name = input("姓名:")
? ? ? ? ? ? head.score = input("分數:")
? ? ? ? ? ? head.next = head
? ? ? ? else: ?# 添加第一個節點之后的節點
? ? ? ? ? ? next_data = Player()
? ? ? ? ? ? next_data.name = input("姓名:")
? ? ? ? ? ? next_data.score = input("分數:")
? ? ? ? ? ? next_data.next = head
? ? ? ? ? ? ptr.next = next_data
?
? ? elif select == "2": ?# 遍歷查看鏈表所有節點
? ? ? ? ergodic(head, is_print=True) ?# 遍歷鏈表,將打印參數設為True
?
? ? elif select == '3': ?# 向鏈表中任意位置插入節點,位置以序號表示,即第一個節點序號為1,第二個節點序號為2,以此類推
? ? ? ? try:
? ? ? ? ? ? num = int(input("請輸入需要插入的節點位置序號:")) ?# 輸入序號必須是大于0的正整數,如果輸入大于最后一個節點的序號則插入到最后一個節點之后
? ? ? ? ? ? if num < 1:
? ? ? ? ? ? ? ? print("輸入必須為大于0的正整數")
? ? ? ? ? ? ? ? continue
? ? ? ? except ValueError:
? ? ? ? ? ? print("輸入有誤")
? ? ? ? ? ? continue
? ? ? ? ptr = ergodic(head, num-1) ?# 獲取需要插入位置的前一個節點
? ? ? ? insert_data = Player()
? ? ? ? insert_data.name = input("姓名:")
? ? ? ? insert_data.score = input("分數:")
? ? ? ? insert_data.next = ptr.next
? ? ? ? ptr.next = insert_data
? ? ? ? if num == 1: ?# 如果插入位置是1的話,那么head將發生變化
? ? ? ? ? ? head = insert_data
?
? ? elif select == '4': ?# 刪除鏈表中任意位置的節點
? ? ? ? try:
? ? ? ? ? ? num = int(input("請輸入需要刪除的節點位置序號:")) ?# 輸入序號必須是大于0的正整數,如果輸入大于最后一個節點的序號則刪除最后一個節點
? ? ? ? ? ? if num < 1:
? ? ? ? ? ? ? ? print("輸入必須為大于0的正整數")
? ? ? ? ? ? ? ? continue
? ? ? ? except ValueError:
? ? ? ? ? ? print("輸入有誤")
? ? ? ? ? ? continue
? ? ? ? ptr = ergodic(head, num - 1) ?# 獲取需要刪除位置的前一個節點
? ? ? ? if ptr == ergodic(head, num): ?# 輸入序號過大時需要做特殊處理,因為輸入序號過大也代表刪除最后一個節點,那么這時我需要獲取這最后一個節點的前一個節點
? ? ? ? ? ? ptr = ergodic(ptr)
? ? ? ? ptr.next = ptr.next.next
? ? ? ? if num == 1: ?# 如果刪除位置是1的話,那么head將發生變化
? ? ? ? ? ? head = ptr.next
?
? ? elif select == '5': ?# 反轉鏈表
? ? ? ? new_first = invert(head) ?# 獲取新的第一個節點
? ? ? ? head = new_first ?# head指向新的第一個節點
? ? ? ? print('成功反轉')
?
? ? elif select == '6':
? ? ? ? print("成功離開")
? ? ? ? break
? ? else:
? ? ? ? print("輸入錯誤,請重試")
部分運行結果如下:
原文鏈接:https://blog.csdn.net/heibuliuqiu_gk/article/details/102650593
相關推薦
- 2022-11-20 Python實現Tracert追蹤TTL值的方法詳解_python
- 2022-04-07 Redis數據庫分布式設計方案介紹_Redis
- 2023-01-13 Pytorch如何加載自己的數據集(使用DataLoader讀取Dataset)_python
- 2022-09-17 python生成requirements.txt文件的推薦方法_python
- 2022-11-18 Redis?存儲對象信息用?Hash?和String的區別_Redis
- 2022-06-22 Git?Bash終端默認路徑的設置查看修改及拓展圖文詳解_其它綜合
- 2023-12-07 mitt 的使用
- 2022-08-02 Docker安裝Redis配置遠程連接及踩坑_docker
- 最近更新
-
- 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同步修改后的遠程分支