python单向循环链表原理与实现方法示例


Posted in Python onDecember 03, 2019

本文实例讲述了python单向循环链表原理与实现方法。分享给大家供大家参考,具体如下:

单向循环链表

单链表的一个变形是单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点。

python单向循环链表原理与实现方法示例

操作

  • is_empty() 判断链表是否为空
  • length() 返回链表的长度
  • travel() 遍历
  • add(item) 在头部添加一个节点
  • append(item) 在尾部添加一个节点
  • insert(pos, item) 在指定位置pos添加节点
  • remove(item) 删除一个节点
  • search(item) 查找节点是否存在

实现

# -*- coding:utf-8 -*-
#! python3
class Node(object):
  """节点"""
  def __init__(self, item):
    self.item = item
    self.next = None
class 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
      # 将尾节点指向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
    while cur.next != self.__head:
      if cur.item == item:
        # 先判断此结点是否是头节点
        if cur == self.__head:
          # 头节点的情况
          # 找尾节点
          rear = self.__head
          while rear.next != self.__head:
            rear = rear.next
          self.__head = cur.next
          rear.next = self.__head
        else:
          # 中间节点
          pre.next = cur.next
        return
      else:
        pre = cur
        cur = cur.next
    # 退出循环,cur指向尾节点
    if cur.item == item:
      if cur == self.__head:
        # 链表只有一个节点
        self.__head = None
      else:
        # pre.next = cur.next
        pre.next = self.__head
  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
if __name__ == "__main__":
  ll = SinCycLinkedlist()
  ll.add(1)
  ll.add(2)
  ll.append(3)
  ll.insert(2, 4)
  ll.insert(4, 5)
  ll.insert(0, 6)
  print("length:", ll.length())
  ll.travel()
  print(ll.search(3))
  print(ll.search(7))
  ll.remove(1)
  print("length:", ll.length())
  ll.travel()

运行结果:

length: 6
6
2
1
4
3
5

True
False
length: 5
6
2
4
3
5

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Python使用matplotlib绘图无法显示中文问题的解决方法
Mar 14 Python
Python读取英文文件并记录每个单词出现次数后降序输出示例
Jun 28 Python
python可视化实现KNN算法
Oct 16 Python
Python 根据数据模板创建shapefile的实现
Nov 26 Python
python3 BeautifulSoup模块使用字典的方法抓取a标签内的数据示例
Nov 28 Python
将python依赖包打包成window下可执行文件bat方式
Dec 26 Python
PyTorch使用cpu加载模型运算方式
Jan 13 Python
解决Pycharm的项目目录突然消失的问题
Jan 20 Python
tensorflow查看ckpt各节点名称实例
Jan 21 Python
python词云库wordcloud的使用方法与实例详解
Feb 17 Python
python异步Web框架sanic的实现
Apr 27 Python
基于python实现监听Rabbitmq系统日志代码示例
Nov 28 Python
使用 Python 清理收藏夹里已失效的网站
Dec 03 #Python
Python常用模块os.path之文件及路径操作方法
Dec 03 #Python
Python中顺序表原理与实现方法详解
Dec 03 #Python
python双向链表原理与实现方法详解
Dec 03 #Python
Python读取实时数据流示例
Dec 02 #Python
简单了解python元组tuple相关原理
Dec 02 #Python
python实现智能语音天气预报
Dec 02 #Python
You might like
php设计模式 Chain Of Responsibility (职责链模式)
2011/06/26 PHP
PHP session_start()问题解疑(详细介绍)
2013/07/05 PHP
table标签的结构与合并单元格的实现方法
2013/07/24 PHP
PHP中用mysqli面向对象打开连接关闭mysql数据库的方法
2016/11/05 PHP
获取页面高度,窗口高度,滚动条高度等参数值getPageSize,getPageScroll
2006/09/22 Javascript
JQuery处理json与ajax返回JSON实例代码
2014/01/03 Javascript
Web前端开发工具——bower依赖包管理工具
2016/03/29 Javascript
使用jQuery Mobile框架开发移动端Web App的入门教程
2016/05/17 Javascript
easyUI实现(alert)提示框自动关闭的实例代码
2016/11/07 Javascript
整理关于Bootstrap警示框的慕课笔记
2017/03/29 Javascript
nodejs入门教程二:创建一个简单应用示例
2017/04/24 NodeJs
js获取浏览器的各种属性
2017/04/27 Javascript
详解Webstorm 新建.vue文件支持高亮vue语法和es6语法
2017/10/26 Javascript
Nuxt.js踩坑总结分享
2018/01/18 Javascript
vue-baidu-map 进入页面自动定位的解决方案(推荐)
2018/04/28 Javascript
用ES6写全屏滚动插件的示例代码
2018/05/02 Javascript
Javascript 实现 Excel 导入生成图表功能
2018/10/22 Javascript
详解微信小程序网络请求接口封装实例
2019/05/02 Javascript
Layui之table中的radio在切换分页时无法记住选中状态的解决方法
2019/09/02 Javascript
layui radio单选限制下一个radio单选的实例
2019/09/03 Javascript
Vue父子之间值传递的实例教程
2020/07/02 Javascript
python中self原理实例分析
2015/04/30 Python
python实现读取命令行参数的方法
2015/05/22 Python
Python matplotlib 画图窗口显示到gui或者控制台的实例
2018/05/24 Python
pandas基于时间序列的固定时间间隔求均值的方法
2019/07/04 Python
利用python实现短信和电话提醒功能的例子
2019/08/08 Python
python conda操作方法
2019/09/11 Python
Python解析json代码实例解析
2019/11/25 Python
SmartBuyGlasses德国:购买太阳镜和眼镜
2019/08/20 全球购物
德国网上超市:myTime.de
2019/08/26 全球购物
矫正人员思想汇报
2014/01/08 职场文书
毕业生自荐书
2014/02/03 职场文书
会计专业应届生自荐信
2014/06/28 职场文书
高一课前三分钟演讲稿
2014/09/13 职场文书
Python实现双向链表
2022/05/25 Python
在SQL Server中使用 Try Catch 处理异常的示例详解
2022/07/15 SQL Server