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中装饰器的用法
Apr 27 Python
Python聚类算法之DBSACN实例分析
Nov 20 Python
机器学习经典算法-logistic回归代码详解
Dec 22 Python
python脚本生成caffe train_list.txt的方法
Apr 27 Python
python+pyqt5实现图片批量缩放工具
Mar 18 Python
Python实现去除图片中指定颜色的像素功能示例
Apr 13 Python
python如何保证输入键入数字的方法
Aug 23 Python
使用pyhon绘图比较两个手机屏幕大小(实例代码)
Jan 03 Python
Ubuntu18.04安装 PyCharm并使用 Anaconda 管理的Python环境
Apr 08 Python
解决Pytorch自定义层出现多Variable共享内存错误问题
Jun 28 Python
python 中关于pycharm选择运行环境的问题
Oct 31 Python
python自动计算图像数据集的RGB均值
Jun 18 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内核学习教程之php opcode内核实现
2016/01/27 PHP
深入理解PHP中的empty和isset函数
2016/05/26 PHP
phpStorm2020 注册码
2020/09/17 PHP
JavaScript Title、alt提示(Tips)实现源码解读
2010/12/12 Javascript
qq悬浮代码(兼容各个浏览器)
2014/01/29 Javascript
jQuery避免$符和其他JS库冲突的方法对比
2014/02/20 Javascript
jquery五角星评分插件示例分享
2014/02/21 Javascript
js类型转换与引用类型详解(Boolean_Number_String)
2014/03/07 Javascript
JQuery中DOM事件绑定用法详解
2015/06/13 Javascript
jQuery页面元素动态添加后绑定事件丢失方法,非 live
2016/06/16 Javascript
jquery实现ajax提交表单信息的简单方法(推荐)
2016/08/24 Javascript
JavaScript结合HTML DOM实现联动菜单
2017/04/05 Javascript
详解vue express启动数据服务
2017/07/05 Javascript
layui监听select变化,以及设置radio选中的方法
2019/09/24 Javascript
[02:12]打造更好的电竞完美世界:完美盛典回顾篇
2018/12/19 DOTA
在Python程序中操作文件之flush()方法的使用教程
2015/05/24 Python
Python数据类型学习笔记
2016/01/13 Python
理解python正则表达式
2016/01/15 Python
Python对文件操作知识汇总
2016/05/15 Python
python利用sklearn包编写决策树源代码
2017/12/21 Python
使用Python制作表情包实现换脸功能
2019/07/19 Python
Django url,从一个页面调到另个页面的方法
2019/08/21 Python
浅析Django中关于session的使用
2019/12/30 Python
浅谈CSS3特性查询(Feature Query: @supports)功能简介
2017/07/31 HTML / CSS
利用简洁的图片预加载组件提升html5移动页面的用户体验
2016/03/11 HTML / CSS
亚洲最大旅游体验平台:KKday
2017/10/21 全球购物
自考生自我鉴定范文
2013/10/01 职场文书
2014年开学第一课活动方案
2014/03/06 职场文书
食品安全工作实施方案
2014/03/26 职场文书
好习惯伴我成长演讲稿
2014/05/21 职场文书
材料专业大学毕业生自荐书
2014/07/02 职场文书
2014年乡镇人大工作总结
2014/11/25 职场文书
见习期个人总结
2015/03/05 职场文书
交通安全教育主题班会
2015/08/12 职场文书
Golang全局变量加锁的问题解决
2021/05/08 Golang
Redis安装使用RedisJSON模块的方法
2022/03/23 Redis