Python数据结构之单链表详解


Posted in Python onSeptember 12, 2017

本文实例为大家分享了Python数据结构之单链表的具体代码,供大家参考,具体内容如下

# 节点类
class Node():
  __slots__=['_item','_next'] # 限定Node实例的属性
  def __init__(self,item):
    self._item = item
    self._next = None # Node的指针部分默认指向None
  def getItem(self):
    return self._item
  def getNext(self):
    return self._next
  def setItem(self,newitem):
    self._item = newitem
  def setNext(self,newnext):
    self._next=newnext

# 单链表
class SingleLinkedList():
  def __init__(self):
    self._head = None #初始化链表为空 始终指向链表的头部
    self._size = 0 # 链表大小

  # 返回链表的大小
  def size(self):
    current = self._head
    count = 0
    while current != None:
      count += 1
      current = current.getNext()
    return count

  # 遍历链表
  def travel(self):
    current = self._head
    while current != None:
      print(current.getItem())
      current = current.getNext()
  # 检查链表是否为空
  def isEmpty(self):
    return self._head == None

  # 在链表前端添加元素
  def add(self,item):
    temp = Node(item) # 创建新的节点
    temp.setNext(self._head) # 新创建的next指针指向_head
    self._head = temp # _head指向新创建的指针

  # 在链表尾部添加元素
  def append(self,item):
    temp = Node(item)
    if self.isEmpty():
      self._head = temp # 若为空表就直接插入
    else:
      current = self._head
      while current.getNext() != None:
        current = current.getNext() # 遍历列表
      current.setNext(temp) # 此时current为链表最后的元素,在末尾插入

  # 检索元素是否在链表中
  def search(self,item):
    current = self._head
    founditem = False
    while current != None and not founditem:
      if current.getItem() == item:
        founditem = True
      else:
        current = current.getNext()
    return founditem

  # 索引元素在表中的位置
  def index(self,item):
    current = self._head
    count = 0
    found = None
    while current != None and not found:
      count += 1
      if current.getItem() == item:
        found = True
      else:
        current = current.getNext()
    if found:
      return count
    else:
      return -1 # 返回-1表示不存在

  # 删除表中的某项元素
  def remove(self,item):
    current = self._head
    pre = None
    while current!=None:
      if current.getItem() == item:
        if not pre:
          self._head = current.getNext()
        else:
          pre.setNext(current.getNext())
        break
      else:
        pre = current
        current = current.getNext()

  # 在链表任意位置插入元素
  def insert(self,pos,item):
    if pos <= 1:
      self.add(item)
    elif pos > self.size():
      self.append(item)
    else:
      temp = Node(item)
      count = 1
      pre = None
      current = self._head
      while count < pos:
        count += 1
        pre = current
        current = current.getNext()
      pre.setNext(temp)
      temp.setNext(current)


if __name__=='__main__':
  a=SingleLinkedList()
  for i in range(1,10):
    a.append(i)
  print('链表的大小',a.size())
  a.travel()
  print(a.search(6))
  print(a.index(5))
  a.remove(4)
  a.travel()
  a.insert(4,100)
  a.travel()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python小技巧之批量抓取美女图片
Jun 06 Python
小结Python用fork来创建子进程注意事项
Jul 03 Python
Python使用functools模块中的partial函数生成偏函数
Jul 02 Python
通过python+selenium3实现浏览器刷简书文章阅读量
Dec 26 Python
python如何读写csv数据
Mar 21 Python
python使用selenium登录QQ邮箱(附带滑动解锁)
Jan 23 Python
python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例
Jun 17 Python
Python爬虫爬取杭州24时温度并展示操作示例
Mar 27 Python
python获取天气接口给指定微信好友发天气预报
Dec 28 Python
Python实战之实现简易的学生选课系统
May 25 Python
OpenCV图像变换之傅里叶变换的一些应用
Jul 26 Python
Python语言中的数据类型-序列
Feb 24 Python
python处理Excel xlrd的简单使用
Sep 12 #Python
Python3.6简单操作Mysql数据库
Sep 12 #Python
Python文件和流(实例讲解)
Sep 12 #Python
Anaconda多环境多版本python配置操作方法
Sep 12 #Python
python 随机数使用方法,推导以及字符串,双色球小程序实例
Sep 12 #Python
python监控linux内存并写入mongodb(推荐)
Sep 11 #Python
python学习教程之Numpy和Pandas的使用
Sep 11 #Python
You might like
一个图形显示IP的PHP程序代码
2007/10/19 PHP
php性能优化分析工具XDebug 大型网站调试工具
2011/05/22 PHP
php实现的九九乘法口诀表简洁版
2014/07/28 PHP
php使用curl_init()和curl_multi_init()多线程的速度比较详解
2018/08/15 PHP
基于jquery的让页面控件不可用的实现代码
2010/04/27 Javascript
8个实用的jQuery技巧
2014/03/04 Javascript
JS制作手机端自适应缩放显示
2015/06/11 Javascript
JS自定义函数实现时间戳转换成date的方法示例
2017/08/27 Javascript
使用mock.js随机数据和使用express输出json接口的实现方法
2018/01/07 Javascript
Vue实现搜索 和新闻列表功能简单范例
2018/03/16 Javascript
JS实现二维数组横纵列转置的方法
2018/04/17 Javascript
React-router4路由监听的实现
2018/08/07 Javascript
微信小程序实现左右列表联动
2020/05/19 Javascript
微信小程序wx.request拦截器使用详解
2019/07/09 Javascript
node express使用HTML模板的方法示例
2019/08/22 Javascript
简单解析Django框架中的表单验证
2015/07/17 Python
独特的python循环语句
2016/11/20 Python
python实现生命游戏的示例代码(Game of Life)
2018/01/24 Python
python使用jieba实现中文分词去停用词方法示例
2018/03/11 Python
python使用matplotlib画柱状图、散点图
2019/03/18 Python
Python实现将字符串的首字母变为大写,其余都变为小写的方法
2019/06/11 Python
Python有参函数使用代码实例
2020/01/06 Python
Python使用Chrome插件实现爬虫过程图解
2020/06/09 Python
Python DataFrame使用drop_duplicates()函数去重(保留重复值,取重复值)
2020/07/20 Python
python根据字典的键来删除元素的方法
2020/08/16 Python
详解python日志输出使用配置文件格式
2021/02/10 Python
CSS3圆角和渐变2种常用功能详解
2016/01/06 HTML / CSS
IE10 Error.stack 让脚本调试更加方便快捷
2013/04/22 HTML / CSS
伦敦高级内衣品牌:Agent Provocateur(大内密探)
2016/08/23 全球购物
澳大利亚最大的护发和护肤品购物网站:RY
2019/12/26 全球购物
网吧收银员岗位职责
2013/12/14 职场文书
销售简历自我评价
2014/01/24 职场文书
葛优非诚勿扰搞笑征婚台词
2014/03/17 职场文书
2014县政府领导班子三严三实对照检查材料思想汇报
2014/09/26 职场文书
2014年大学班长工作总结
2014/11/14 职场文书
小学安全教育主题班会
2015/08/12 职场文书