python描述单向循环链表
来源:互联网 发布:阿里推送 js sdk 编辑:程序博客网 时间:2024/05/16 15:29
单链表的一个变形就是单向循环链表,链表中最后一个节点的next域不在为None,而是指向链表的头节点
操作
- is_empty() 判空
- length() 求长度
- travel() 遍历
- add(item) 头部插入
- append(item) 尾部插入
- insert(pos,item) 在指定位置插入
- remove(item) 删除一个节点
- search(item) 查找一个节点是否存在
实现
class Node(object): """节点""" def __init__(self,item): self.item = item self.next = Noneclass SinCycLinkedlist(object): """单向循环链表""" def __init__(self): self._head = None def is_empty(self): """判断链表是否为空""" return self._head == None def length(self): """返回链表长度""" # 如果链表为空,返回长度0 if self.is_empty(): return 0 count = 1 cur = self._head while cur.next != self._head: count += 1 cur = cur.next return count def travel(self): """遍历链表""" if self.is_empty(): return cur = self._head print(cur.item) while cur.next != self._head: cur = cur.next print(cur.item) print(" ") def add(self,item): """头部添加节点""" node = Node(item) if self.is_empty(): self._head = node node.next = self._head else: # 添加节点指向_head node.next = self._head # 移到链表尾部,将尾部节点的next指向node cur = self._head while cur.next != self._head: cur = cur.next cur.next = node # _head指向node self._head = node def append(self,item): """尾部添加节点""" node = Node(item) if self.is_empty(): self._head = node node.next = self._head else: #移到链表尾部 cur = self._head while cur.next != self._head: cur = cur.next # 将尾节点的next指向node cur.next = node # 将node指向头节点_head node.next = self._head def insert(self,pos,item): """在指定位置添加节点""" if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: node = Node(item) cur = self._head count = 0 # 移到指定位置的前一个位置 while count < (pos-1): count += 1 cur = cur.next node.next = cur.next cur.next = node def remove(self,item): """删除一个节点""" # 若链表为空,则直接返回 if self.is_empty(): return # 将cur指向头节点 cur = self._head pre = None # 若头节点的元素就是要查找的元素item if cur.item == item: # 如果链表不止一个节点 if cur.next != self._head: # 先找到尾节点,将尾节点的next指向第二个节点 while cur.next != self._head: cur = cur.next # cur指向了尾节点 cur.next = self._head.next self._head = self._head.next else: # 链表只有一个节点 self._head = None else: pre = self._head # 第一个节点不是要删除的 while cur.next != self._head: # 找到了要删除的元素 if cur.item == item: # 删除 pre.next = cur.next return else: pre = cur cur = cur.next # cur 指向尾节点 if cur.item == item: # 尾部删除 pre.next = cur.next def search(self,item): """查找节点是否存在""" if self.is_empty(): return False cur = self._head if cur.item == item: return True while cur.next != self._head: cur = cur.next if cur.item == item: return True return False
阅读全文
0 0
- python描述单向循环链表
- 单向循环链表
- 单向循环链表
- 单向循环链表
- 单向循环链表
- 循环单向链表
- 单向循环链表
- 循环单向链表
- 单向链表循环
- 循环单向链表
- 单向循环链表
- 单向循环链表
- 单向循环链表
- 单向循环链表
- 单向循环链表
- 单向循环链表
- <数据结构与算法>单向循环链表基本框架(C语言描述)
- 单向循环链表反转
- Python字符串操作
- 蓝牙4.0BLE抓包(三) – 扫描请求和扫描响应
- 十一、容器集群的管理(k8S、Swarm)
- Maven生命周期
- 3
- python描述单向循环链表
- hdu 5444Elven Postman(建树,遍历)
- 51Nod
- Matlab图像的几何变换之图像平移
- Mybatis DAO层参数传递
- JAVA多线程编程——1.9线程让步-1.11守护线程
- HOJ 3188
- LaTeX大括号公式和一般括号总结
- WireShark查看指定的PC应用的网络包