看此博客之前建议先看看B站的视频python数据结构与算法系列课程,该课程中未实现双向循环链表的操作,所以我按照该视频的链表思路实现了双向循环链表的操作,欢迎大家阅读与交流,如有侵权,请联系博主!
下面附上代码:
class Node: def __init__(self, elem): self.elem = elem self.prev = None self.next = None class DoubleCycleLinkList: def __init__(self, node=None): self.__head = node def is_empty(self): """判空""" if self.__head is None: return True return False def length(self): """链表长度""" if self.is_empty(): return 0 cur = self.__head count = 1 while cur.next is not self.__head: count += 1 cur = cur.next return count def travel(self): """遍历链表""" if self.is_empty(): return cur = self.__head while cur.next is not self.__head: print(cur.elem, end=" ") cur = cur.next print(cur.elem, end=" ") print("") def add(self, elem): """头插法""" node = Node(elem) if self.is_empty(): self.__head = node node.prev = node node.next = node else: self.__head.prev.next = node node.prev = self.__head.prev node.next = self.__head self.__head.prev = node self.__head = node def append(self, elem): """尾插法""" node = Node(elem) if self.is_empty(): self.__head = node node.prev = node node.next = node else: node.next = self.__head node.prev = self.__head.prev self.__head.prev.next = node self.__head.prev = node def insert(self, pos, elem): """任一位置(pos)插入, 下标从0数起""" if pos <= 0: self.add(elem) elif pos > (self.length() - 1): self.append(elem) else: count = 0 cur = self.__head node = Node(elem) while count < (pos - 1): count += 1 cur = cur.next node.next = cur.next node.prev = cur node.next.prev = node cur.next = node def remove(self, elem): """删除某一节点,若有多个符合条件的节点,删除第一个即可""" if self.is_empty(): return cur = self.__head while cur.next is not self.__head: if cur.elem == elem: if cur is self.__head: self.__head = cur.next cur.prev.next = cur.next cur.next.prev = cur.prev else: cur.prev.next = cur.next cur.next.prev = cur.prev break cur = cur.next if cur.elem == elem: cur.prev.next = self.__head self.head = cur.prev def search(self, elem): """查找某一个节点""" if self.is_empty(): return False cur = self.__head while cur.next is not self.__head: if cur.elem == elem: return True cur = cur.next # while中处理不到尾节点,所以进行最后尾节点的判断 if cur.elem == elem: return True return False
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“python实现数据结构中双向循环链表操作的示例”评论...
更新日志
2024年11月08日
2024年11月08日
- 雨林唱片《赏》新曲+精选集SACD版[ISO][2.3G]
- 罗大佑与OK男女合唱团.1995-再会吧!素兰【音乐工厂】【WAV+CUE】
- 草蜢.1993-宝贝对不起(国)【宝丽金】【WAV+CUE】
- 杨培安.2009-抒·情(EP)【擎天娱乐】【WAV+CUE】
- 周慧敏《EndlessDream》[WAV+CUE]
- 彭芳《纯色角3》2007[WAV+CUE]
- 江志丰2008-今生为你[豪记][WAV+CUE]
- 罗大佑1994《恋曲2000》音乐工厂[WAV+CUE][1G]
- 群星《一首歌一个故事》赵英俊某些作品重唱企划[FLAC分轨][1G]
- 群星《网易云英文歌曲播放量TOP100》[MP3][1G]
- 方大同.2024-梦想家TheDreamer【赋音乐】【FLAC分轨】
- 李慧珍.2007-爱死了【华谊兄弟】【WAV+CUE】
- 王大文.2019-国际太空站【环球】【FLAC分轨】
- 群星《2022超好听的十倍音质网络歌曲(163)》U盘音乐[WAV分轨][1.1G]
- 童丽《啼笑姻缘》头版限量编号24K金碟[低速原抓WAV+CUE][1.1G]