網(wǎng)站首頁 編程語言 正文
單向鏈表每個節(jié)點都是由兩部分組成:數(shù)據(jù)字段和指針,指針指向下一個元素在內(nèi)存中的位置。
單向鏈表的第一個節(jié)點節(jié)點是鏈表頭指針,而最后一個節(jié)點的指針設(shè)為None,不指向任何元素。(鏈表頭指針相當(dāng)重要!!!)
使用Python實現(xiàn)單向鏈表,我們可以使用一個節(jié)點類來封裝節(jié)點,每創(chuàng)建一個節(jié)點就生成一個節(jié)點類的實例。
這里主要實現(xiàn)了單向鏈表節(jié)點的遍歷、添加、插入、刪除,反轉(zhuǎn)。
代碼如下:
class Player:
? ? """節(jié)點類"""
? ? def __init__(self):
? ? ? ? """初始化姓名,分數(shù),指針"""
? ? ? ? self.name = ''
? ? ? ? self.score = 0
? ? ? ? self.next = None
?
?
def ergodic(head, num=None, is_print=False):
? ? """遍歷函數(shù),num是遍歷到哪一個位置序號,is_print是否觸發(fā)打印方法"""
? ? ptr = head
? ? count = 0
? ? while True:
? ? ? ? if num == count:
? ? ? ? ? ? break
? ? ? ? if ptr.next:
? ? ? ? ? ? count += 1
? ? ? ? ? ? ptr = ptr.next
? ? ? ? ? ? if is_print:
? ? ? ? ? ? ? ? print('No.'+str(count), ptr.name, ptr.score, '--->', ptr.next.name if ptr.next else None)
? ? ? ? else:
? ? ? ? ? ? break
? ? return ptr ?# 返回遍歷完成后的最后一個節(jié)點
?
?
def invert(x): ?# x是鏈表的第一個節(jié)點(即head的指針的指向)
? ? """反轉(zhuǎn)鏈表"""
? ? y = x.next ?# y是x原來的next
? ? if y is None: ?# y等于None表示當(dāng)前鏈表只有一個節(jié)點
? ? ? ? return x
? ? x.next = None ?# 將第一個節(jié)點的next指向None(因為反轉(zhuǎn)了)
? ? while True: ?# 循環(huán)反轉(zhuǎn)后面的所有節(jié)點
? ? ? ? r = y.next
? ? ? ? y.next = x
? ? ? ? if r is None: ?# r是None說明y已經(jīng)是原本鏈表的最后一個節(jié)點了
? ? ? ? ? ? return y ?# 返回y,這個y是反轉(zhuǎn)后的鏈表的第一個節(jié)點
? ? ? ? x = y
? ? ? ? y = r
?
?
head = Player()
?
?
while True:
? ? select = input("(1).新增 ? (2).查看 ? (3).插入 ? (4).刪除 ? (5).反轉(zhuǎn) ? (6).離開\n輸入:")
? ? if select == "1": ?# 新增節(jié)點
? ? ? ? ptr = ergodic(head) ?# 獲取當(dāng)前鏈表最后一個節(jié)點
? ? ? ? next_data = Player() ?# 創(chuàng)建一個新節(jié)點
? ? ? ? next_data.name = input("姓名:")
? ? ? ? next_data.score = input("分數(shù):")
? ? ? ? next_data.next = None
? ? ? ? ptr.next = next_data ?# 連接節(jié)點
? ? ? ??
? ? elif select == "2": ?# 遍歷查看鏈表所有節(jié)點
? ? ? ? print("所有數(shù)據(jù)顯示如下:")
? ? ? ? ergodic(head, is_print=True) ?# 遍歷鏈表,將打印參數(shù)設(shè)為True
? ? ? ??
? ? elif select == '3': ?# 向鏈表中任意位置插入節(jié)點,位置以序號表示,即第一個節(jié)點序號為1,第二個節(jié)點序號為2,以此類推
? ? ? ? try:
? ? ? ? ? ? num = int(input("請輸入需要插入的節(jié)點位置序號:")) ?# 輸入序號必須是大于0的正整數(shù),如果輸入大于最后一個節(jié)點的序號則插入到最后一個節(jié)點之后
? ? ? ? ? ? if num < 1:
? ? ? ? ? ? ? ? print("輸入必須為大于0的正整數(shù)")
? ? ? ? ? ? ? ? continue
? ? ? ? except ValueError:
? ? ? ? ? ? print("輸入有誤")
? ? ? ? ? ? continue
? ? ? ? ptr = ergodic(head, num-1) ?# 獲取需要插入位置的前一個節(jié)點
? ? ? ? insert_data = Player()
? ? ? ? insert_data.name = input("姓名:")
? ? ? ? insert_data.score = input("分數(shù):")
? ? ? ? insert_data.next = ptr.next
? ? ? ? ptr.next = insert_data
? ? ? ??
? ? elif select == '4': ?# 刪除鏈表中任意位置的節(jié)點
? ? ? ? try:
? ? ? ? ? ? num = int(input("請輸入需要刪除的節(jié)點位置序號:")) ?# 輸入序號必須是大于0的正整數(shù),如果輸入大于最后一個節(jié)點的序號則刪除最后一個節(jié)點
? ? ? ? ? ? if num < 1:
? ? ? ? ? ? ? ? print("輸入必須為大于0的正整數(shù)")
? ? ? ? ? ? ? ? continue
? ? ? ? except ValueError:
? ? ? ? ? ? print("輸入有誤")
? ? ? ? ? ? continue
? ? ? ? ptr = ergodic(head, num - 1) ?# 獲取需要刪除位置的前一個節(jié)點
? ? ? ? ptr.next = ptr.next.next
? ? ? ??
? ? elif select == '5': ?# 反轉(zhuǎn)鏈表
? ? ? ? new_first = invert(head.next) ?# 獲取新的第一個節(jié)點
? ? ? ? head.next = new_first ?# head指向新的第一個節(jié)點
? ? ? ? print('成功反轉(zhuǎn)')
? ? ? ??
? ? elif select == '6':
? ? ? ? print("成功離開")
? ? ? ? break
? ? else:
? ? ? ? print("輸入錯誤,請重試")
部分運行結(jié)果:
原文鏈接:https://blog.csdn.net/heibuliuqiu_gk/article/details/102641541
相關(guān)推薦
- 2023-07-09 關(guān)于 axios 是什么?以及怎么用?
- 2023-04-07 React?Fiber構(gòu)建源碼解析_React
- 2023-02-09 C++存儲持續(xù)性生命周期原理解析_C 語言
- 2022-10-27 React狀態(tài)管理Redux原理與介紹_React
- 2023-02-15 C#?9使用foreach擴展的示例詳解_C#教程
- 2022-06-24 使用python?matplotlib畫折線圖實例代碼_python
- 2022-05-15 Qt Linux獲取bios ID作為唯一標(biāo)識
- 2022-05-27 Python?內(nèi)置函數(shù)sorted()的用法_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支