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将xml和xsl转换为html的方法
Mar 10 Python
Python 单元测试(unittest)的使用小结
Nov 14 Python
Python中作用域的深入讲解
Dec 10 Python
Python使用while循环花式打印乘法表
Jan 28 Python
Python3字符串encode与decode的讲解
Apr 02 Python
python 反编译exe文件为py文件的实例代码
Jun 27 Python
Python3内置模块之base64编解码方法详解
Jul 13 Python
基于Python批量生成指定尺寸缩略图代码实例
Nov 20 Python
Django values()和value_list()的使用
Mar 31 Python
Python 多线程共享变量的实现示例
Apr 17 Python
django项目中使用云片网发送短信验证码的实现
Jan 19 Python
Python 如何利用ffmpeg 处理视频素材
Nov 27 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地址引用(php地址引用的效率问题)
2012/03/23 PHP
php-perl哈希算法实现(times33哈希算法)
2013/12/30 PHP
PHP定时更新程序设计思路分享
2014/06/10 PHP
Firefox getBoxObjectFor getBoundingClientRect联系
2008/10/26 Javascript
jQuery EasyUI API 中文文档 - NumberSpinner数值微调器使用介绍
2011/10/21 Javascript
JS预览图像将本地图片显示到浏览器上
2013/08/25 Javascript
jquery each的几种常用的使用方法示例
2014/01/21 Javascript
Jquery异步提交表单代码分享
2015/03/26 Javascript
JQuery自动触发事件的方法
2015/06/13 Javascript
如何使用AngularJs打造权限管理系统【简易型】
2016/05/09 Javascript
jquery+html仿翻页相册功能
2016/12/20 Javascript
老生常谈jquery中detach()和remove()的区别
2017/03/02 Javascript
vue学习笔记之指令v-text &amp;&amp; v-html &amp;&amp; v-bind详解
2017/05/12 Javascript
Textarea输入字数限制实例(兼容iOS&amp;安卓)
2017/07/06 Javascript
vue实现添加与删除图书功能
2018/10/07 Javascript
vue router带参数页面刷新或回退参数消失的解决方法
2019/02/27 Javascript
Js实现粘贴上传图片的原理及示例
2020/12/09 Javascript
vue 动态添加的路由页面刷新时失效的原因及解决方案
2021/02/26 Vue.js
pandas数值计算与排序方法
2018/04/12 Python
Django数据库连接丢失问题的解决方法
2018/12/29 Python
python使用matplotlib绘制雷达图
2019/10/18 Python
python 实现按对象传值
2019/12/26 Python
python环境下安装opencv库的方法
2020/03/05 Python
CSS3实现div从下往上滑入滑出效果示例
2020/04/28 HTML / CSS
人力资源经理的岗位职责
2014/03/02 职场文书
骨干教师考核方案
2014/05/09 职场文书
民族团结先进个人事迹材料
2014/06/02 职场文书
防邪知识进家庭活动方案
2014/08/26 职场文书
关于教师节的演讲稿
2014/09/04 职场文书
2014年学生会个人工作总结
2014/11/07 职场文书
2014年扶贫工作总结
2014/11/18 职场文书
2014年合同管理工作总结
2014/12/02 职场文书
2015年度党风廉政建设工作情况汇报
2015/01/02 职场文书
2015年村党支部工作总结
2015/04/30 职场文书
分享15个Webpack实用的插件!!!
2021/03/31 Javascript
详解Redis主从复制实践
2021/05/19 Redis