首页 / PYTHON / python实现单向链表
python实现单向链表
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python实现单向链表,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2520字,纯文字阅读大概需要4分钟。
内容图文
# 节点类 class Node: def __init__(self, data, next=None): self.data = data self.next = next def__str__(self): return str(self.data) # 链表类class LinkedList: def__init__(self): self.head = None self.length = 0 # 链表尾部append数据def append(self, data): node = Node(data) if self.head is None: # head 未空,则此时链表为空,直接将新节点赋给self.head self.head = node else: # head 不为空 current = self.head index = 0 while current.next: # 当前元素的下个元素是否为空 current = current.next current.next = node self.length += 1 # 某一位置插入节点def insert(self, pos, data): if pos < 0 or pos > self.length: raise IndexError new_node = Node(data) # 创建新的节点# pos 为 0时if pos == 0: # 插入到第一个位置,因为有head所以需要单独处理 new_node.next = self.head self.head = new_node self.length += 1 return# pos不为0时 count = 0 # 记录遍历过的节点数 previous = None # 当前节点的前一个节点 current = self.head # 当前节点,从第一个节点开始遍历,所以默认为headwhile count < pos: # 遍历到pos的前一个节点 count += 1 previous = current current = current.next previous.next = new_node # 循环结束后,将新的节点赋给previous.next new_node.next = current # 将当前节点赋给 new_node.next self.length += 1 # integer -- return first index of value.def index(self, value) -> int: index = 0 current = self.head while current: if current.data == value: return index current = current.next index += 1 return -1 # index -> valuedef valueof(self, index): count = 0 current = self.head while current: if index == count: return current.data current = current.next count += 1 return‘‘# 移除某一个节点def remove(self, value): current = self.head previous = None index = 0 # 分两种情况 1、移除的节点是第一个节点(index=0), 2、移除的节点不是第一个节点(index !=0)while current: if current.data == value: print(‘remove‘) if index == 0: self.head = current.next else: previous.next = current.next return previous = current current = current.next def update(self, index, new_value): current = self.head count = 0 while current: if index == count: current.data = new_value return current.data current = current.data def__str__(self): tostr = ‘LinkedList { ‘ current = self.head while current: tostr = tostr + str(current) + "" current = current.next return tostr + ‘}‘# 测试代码 linklist = LinkedList() linklist.append(‘1‘) linklist.append(‘2‘) linklist.append(‘3‘) linklist.append(‘4‘) linklist.append(‘5‘) linklist.insert(0, ‘a‘) print(linklist) print(linklist.length) print(linklist.index(‘3‘)) print(linklist.valueof(1)) print(linklist) linklist.remove(‘a‘) print(linklist) print(linklist.update(0, ‘b‘)) print(linklist) print(linklist.update(0, ‘c‘)) print(linklist)
原文:https://www.cnblogs.com/yaoqingzhuan/p/12213687.html
内容总结
以上是互联网集市为您收集整理的python实现单向链表全部内容,希望文章能够帮你解决python实现单向链表所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。