python数据结构之链表详解


Posted in Python onSeptember 12, 2017

数据结构是计算机科学必须掌握的一门学问,之前很多的教材都是用C语言实现链表,因为c有指针,可以很方便的控制内存,很方便就实现链表,其他的语言,则没那么方便,有很多都是用模拟链表,不过这次,我不是用模拟链表来实现,因为python是动态语言,可以直接把对象赋值给新的变量。

好了,在说我用python实现前,先简单说说链表吧。在我们存储一大波数据时,我们很多时候是使用数组,但是当我们执行插入操作的时候就是非常麻烦,看下面的例子,有一堆数据1,2,3,5,6,7我们要在3和5之间插入4,如果用数组,我们会怎么做?当然是将5之后的数据往后退一位,然后再插入4,这样非常麻烦,但是如果用链表,我就直接在3和5之间插入4就行,听着就很方便。

那么链表的结构是怎么样的呢?顾名思义,链表当然像锁链一样,由一节节节点连在一起,组成一条数据链。

链表的节点的结构如下:

python数据结构之链表详解

data为自定义的数据,next为下一个节点的地址。

链表的结构为,head保存首位节点的地址:

python数据结构之链表详解

接下来我们来用python实现链表

python实现链表

首先,定义节点类Node:

class Node:
  '''
  data: 节点保存的数据
  _next: 保存下一个节点对象
  '''
  def __init__(self, data, pnext=None):
    self.data = data
    self._next = pnext

  def __repr__(self):
    '''
    用来定义Node的字符输出,
    print为输出data
    '''
    return str(self.data)

然后,定义链表类:

链表要包括:

属性:

链表头:head

链表长度:length

方法:

判断是否为空: isEmpty()

def isEmpty(self):
  return (self.length == 0

增加一个节点(在链表尾添加): append()

def append(self, dataOrNode):
  item = None
  if isinstance(dataOrNode, Node):
    item = dataOrNode
  else:
    item = Node(dataOrNode)

  if not self.head:
    self.head = item
    self.length += 1

  else:
    node = self.head
    while node._next:
      node = node._next
    node._next = item
    self.length += 1

删除一个节点: delete()

#删除一个节点之后记得要把链表长度减一
def delete(self, index):
  if self.isEmpty():
    print "this chain table is empty."
    return

  if index < 0 or index >= self.length:
    print 'error: out of index'
    return
  #要注意删除第一个节点的情况
  #如果有空的头节点就不用这样
  #但是我不喜欢弄头节点
  if index == 0:
    self.head = self.head._next
    self.length -= 1
    return

  #prev为保存前导节点
  #node为保存当前节点
  #当j与index相等时就
  #相当于找到要删除的节点
  j = 0
  node = self.head
  prev = self.head
  while node._next and j < index:
    prev = node
    node = node._next
    j += 1

  if j == index:
    prev._next = node._next
    self.length -= 1

修改一个节点: update()

def update(self, index, data):
  if self.isEmpty() or index < 0 or index >= self.length:
    print 'error: out of index'
    return
  j = 0
  node = self.head
  while node._next and j < index:
    node = node._next
    j += 1

  if j == index:
    node.data = data

查找一个节点: getItem()

def getItem(self, index):
  if self.isEmpty() or index < 0 or index >= self.length:
    print "error: out of index"
    return
  j = 0
  node = self.head
  while node._next and j < index:
    node = node._next
    j += 1

  return node.data

查找一个节点的索引: getIndex()

def getIndex(self, data):
  j = 0
  if self.isEmpty():
    print "this chain table is empty"
    return
  node = self.head
  while node:
    if node.data == data:
      return j
    node = node._next
    j += 1

  if j == self.length:
    print "%s not found" % str(data)
    return

插入一个节点: insert()

def insert(self, index, dataOrNode):
  if self.isEmpty():
    print "this chain tabale is empty"
    return

  if index < 0 or index >= self.length:
    print "error: out of index"
    return

  item = None
  if isinstance(dataOrNode, Node):
    item = dataOrNode
  else:
    item = Node(dataOrNode)

  if index == 0:
    item._next = self.head
    self.head = item
    self.length += 1
    return

  j = 0
  node = self.head
  prev = self.head
  while node._next and j < index:
    prev = node
    node = node._next
    j += 1

  if j == index:
    item._next = node
    prev._next = item
    self.length += 1

清空链表: clear()

def clear(self):
  self.head = None
  self.length = 0

以上就是链表类的要实现的方法。

执行的结果:

python数据结构之链表详解

python数据结构之链表详解

python数据结构之链表详解

接下来是完整代码:

# -*- coding:utf8 -*-
#/usr/bin/env python

class Node(object):
 def __init__(self, data, pnext = None):
  self.data = data
  self._next = pnext

 def __repr__(self):
  return str(self.data)

class ChainTable(object):
 def __init__(self):
  self.head = None
  self.length = 0

 def isEmpty(self):
  return (self.length == 0)

 def append(self, dataOrNode):
  item = None
  if isinstance(dataOrNode, Node):
   item = dataOrNode
  else:
   item = Node(dataOrNode)

  if not self.head:
   self.head = item
   self.length += 1

  else:
   node = self.head
   while node._next:
    node = node._next
   node._next = item
   self.length += 1

 def delete(self, index):
  if self.isEmpty():
   print "this chain table is empty."
   return

  if index < 0 or index >= self.length:
   print 'error: out of index'
   return

  if index == 0:
   self.head = self.head._next
   self.length -= 1
   return

  j = 0
  node = self.head
  prev = self.head
  while node._next and j < index:
   prev = node
   node = node._next
   j += 1

  if j == index:
   prev._next = node._next
   self.length -= 1

 def insert(self, index, dataOrNode):
  if self.isEmpty():
   print "this chain tabale is empty"
   return

  if index < 0 or index >= self.length:
   print "error: out of index"
   return

  item = None
  if isinstance(dataOrNode, Node):
   item = dataOrNode
  else:
   item = Node(dataOrNode)

  if index == 0:
   item._next = self.head
   self.head = item
   self.length += 1
   return

  j = 0
  node = self.head
  prev = self.head
  while node._next and j < index:
   prev = node
   node = node._next
   j += 1

  if j == index:
   item._next = node
   prev._next = item
   self.length += 1

 def update(self, index, data):
  if self.isEmpty() or index < 0 or index >= self.length:
   print 'error: out of index'
   return
  j = 0
  node = self.head
  while node._next and j < index:
   node = node._next
   j += 1

  if j == index:
   node.data = data

 def getItem(self, index):
  if self.isEmpty() or index < 0 or index >= self.length:
   print "error: out of index"
   return
  j = 0
  node = self.head
  while node._next and j < index:
   node = node._next
   j += 1

  return node.data


 def getIndex(self, data):
  j = 0
  if self.isEmpty():
   print "this chain table is empty"
   return
  node = self.head
  while node:
   if node.data == data:
    return j
   node = node._next
   j += 1

  if j == self.length:
   print "%s not found" % str(data)
   return

 def clear(self):
  self.head = None
  self.length = 0

 def __repr__(self):
  if self.isEmpty():
   return "empty chain table"
  node = self.head
  nlist = ''
  while node:
   nlist += str(node.data) + ' '
   node = node._next
  return nlist

 def __getitem__(self, ind):
  if self.isEmpty() or ind < 0 or ind >= self.length:
   print "error: out of index"
   return
  return self.getItem(ind)

 def __setitem__(self, ind, val):
  if self.isEmpty() or ind < 0 or ind >= self.length:
   print "error: out of index"
   return
  self.update(ind, val)

 def __len__(self):
  return self.length

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

Python 相关文章推荐
python选择排序算法实例总结
Jul 01 Python
python:socket传输大文件示例
Jan 18 Python
python实现给微信公众号发送消息的方法
Jun 30 Python
Python 实现购物商城,含有用户入口和商家入口的示例
Sep 15 Python
使用sklearn进行对数据标准化、归一化以及将数据还原的方法
Jul 11 Python
Python读取指定日期邮件的实例
Feb 01 Python
Python基于opencv实现的简单画板功能示例
Mar 04 Python
Python函数中参数是传递值还是引用详解
Jul 02 Python
Python Handler处理器和自定义Opener原理详解
Mar 05 Python
Python实现发票自动校核微信机器人的方法
May 22 Python
Python实现清理微信僵尸粉功能示例【基于itchat模块】
May 29 Python
Python3中的tuple函数知识点讲解
Jan 03 Python
Python数据结构之单链表详解
Sep 12 #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
You might like
PHP中上传大体积文件时需要的设置
2006/10/09 PHP
PHP安装攻略:常见问题解答(三)
2006/10/09 PHP
php数组函数序列 之array_count_values() 统计数组中所有值出现的次数函数
2011/10/29 PHP
php树型类实例
2014/12/05 PHP
php第一次无法获取cookie问题处理
2014/12/15 PHP
php实现根据IP地址获取其所在省市的方法
2015/04/30 PHP
PHP实现的mysql主从数据库状态检测功能示例
2017/07/20 PHP
PHP使用PDO操作sqlite数据库应用案例
2019/03/07 PHP
ExtJS Grid使用SimpleStore、多选框的方法
2009/11/20 Javascript
javascript运行机制之this详细介绍
2014/02/07 Javascript
JS实现表格数据各种搜索功能的方法
2015/03/03 Javascript
JS实现的数组全排列输出算法
2015/03/19 Javascript
JavaScript实现把rgb颜色转换成16进制颜色的方法
2015/06/01 Javascript
基于Css3和JQuery实现打字机效果
2015/08/11 Javascript
js与jQuery实现checkbox复选框全选/全不选的方法
2016/01/05 Javascript
JS简单实现数组去重的方法示例
2017/03/27 Javascript
详解Vue微信授权登录前后端分离较为优雅的解决方案
2018/06/29 Javascript
vue做移动端适配最佳解决方案(亲测有效)
2018/09/04 Javascript
原生JS实现音乐播放器
2021/01/26 Javascript
python验证码识别教程之滑动验证码
2018/06/04 Python
Pandas GroupBy对象 索引与迭代方法
2018/11/16 Python
pycharm新建一个python工程步骤
2019/07/16 Python
python使用列表的最佳方案
2020/08/12 Python
python爬虫中PhantomJS加载页面的实例方法
2020/11/12 Python
Pytorch 中的optimizer使用说明
2021/03/03 Python
CSS3对图片照片进行边缘模糊处理的实现
2018/08/08 HTML / CSS
新闻学专业大学生职业生涯规划范文
2014/03/02 职场文书
会计核算科岗位职责
2014/03/19 职场文书
医学专业毕业生求职信
2014/06/20 职场文书
开展党的群众路线教育实践活动剖析材料
2014/10/13 职场文书
申论不会写怎么办?教您掌握这6点思维和原则
2019/07/17 职场文书
Idea连接MySQL数据库出现中文乱码的问题
2021/04/14 MySQL
教你使用pyinstaller打包Python教程
2021/05/27 Python
Golang生成Excel文档的方法步骤
2021/06/09 Golang
JUnit5常用注解的使用
2021/07/02 Java/Android
Linux系统下MySQL配置主从分离的步骤
2022/03/21 MySQL