数据结构与算法——单项链表
2020-01-15 05:42
99 查看
class SingleNode(object): # 创建节点 def __init__(self, item): # item是节点数据 self.item = item self.next = None class SingleLinkList(object): # 创建头节点 def __init__(self, node = None): self._head = node self._length = 0 # 判断表是否为空 @property def emtpy(self): return self._head == None # 表长 @property def length(self): return self._length # 头插法 def HeadInsert(self, value): node = SingleNode(value) node.item = value node.next = self._head self._head = node self._length += 1 # 尾插法 def TailInsert(self, value): node = SingleNode(value) if self.emtpy: self._head = node else: tmp = self._head while tmp.next != None: tmp = tmp.next tmp.next = node self._length += 1 # 指定位置插入 def Insert(self, pos, value): if isinstance(pos, int) == False: print("请输入正确的位置!") return if pos <= 0: self.HeadInsert(value) elif pos > self._length - 1: self.TailInsert(value) else: node = SingleNode(value) count = 0 tmp = self._head while count < pos - 1: tmp = tmp.next count += 1 node.next = tmp.next tmp.next = node self._length += 1 # 指定位置删除 def pop(self, pos): if isinstance(pos, int) == False: print("请输入正确的位置!") return if pos <= 0: tmp = self._head self._head = tmp.next self._length -= 1 return tmp.item elif pos >= self._length: tmp = self._head count = 0 while count <= self._length - 3: tmp = tmp.next count += 1 value = tmp.next.item tmp.next = tmp.next.next self._length -= 1 return value else: tmp = self._head count = 0 while count <= pos - 2: tmp = tmp.next count += 1 value = tmp.next.item tmp.next = tmp.next.next self._length -= 1 return value # 删除指定元素 def Delete(self, value): tmp = self._head while True: try: if tmp.next.item == value: break else: tmp = tmp.next except AttributeError: print("未找到该元素!") return tmp.next = tmp.next.next self._length -= 1 # 得到指定位置的值 def Getitem(self, pos): if self._length == 0: print("链表为空!") return if isinstance(pos, int) == False: print("请输入正确的位置!") tmp = self._head if pos <= 0: return tmp.item elif pos >= self._length: while tmp.next: tmp = tmp.next return tmp.item else: count = 0 while count < pos: tmp = tmp.next count += 1 return tmp.item # 销毁链表 def Destroy(self): self._head = None # 遍历单链表,返回列表 def Travel(self): tmp = self._head list_item = [] while tmp.next: list_item.append(tmp.item) tmp = tmp.next list_item.append(tmp.item) return list_item if __name__ == '__main__': s = SingLinkList()
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- java的数据结构与算法(7)单项链表之百度面试题
- java的数据结构与算法(4)单项链表
- CPP单项链表插入数据初试
- Java实现数据结构与算法-链表与双向链表
- 数据结构与算法 | 线性表 —— 链表
- 数据结构与算法系列---单链表
- 数据结构与算法学习笔记(2)数组与链表
- 数据结构与算法 ---- 线性表 及Java实现 顺序表、链表、栈、队列
- 数据结构与算法学习 第1季02 链表的基本功能 C++实现
- 《数据结构与算法》学习笔记13 单链表和双端链表
- 数据结构与算法(C语言)之循环链表(单链表)
- java的数据结构与算法(8)双向链表
- 数据结构与算法 2:双向链表,栈,队列
- 数据结构与算法中单链表的部分操作
- 程序员求职之道(《程序员面试笔试宝典》)之数据结构与算法(数组和链表的区别)?
- java数据结构与算法之顺序表与链表深入分析
- 单向链表,单项循环链表,双向链表
- 数据结构与算法-“数组、链表、树、哈希表”选哪个(性能比较)?
- Day12-实战(单项链表循环-通讯录)
- 数据结构与算法-简单链表实现