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获取豆瓣电影简介代码分享
Jan 16 Python
Windows下PyMongo下载及安装教程
Apr 27 Python
python基于右递归解决八皇后问题的方法
May 25 Python
详解Python装饰器由浅入深
Dec 09 Python
python和flask中返回JSON数据的方法
Mar 26 Python
Python完成哈夫曼树编码过程及原理详解
Jul 29 Python
python使用 __init__初始化操作简单示例
Sep 26 Python
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
Oct 06 Python
Python内置数据类型list各方法的性能测试过程解析
Jan 07 Python
Python发起请求提示UnicodeEncodeError错误代码解决方法
Apr 21 Python
python使用matplotlib:subplot绘制多个子图的示例
Sep 24 Python
Django启动时找不到mysqlclient问题解决方案
Nov 11 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下操作Linux消息队列完成进程间通信的方法
2010/07/24 PHP
ThinkPHP登录功能的实现方法
2014/08/20 PHP
php读取文件内容到数组的方法
2015/03/16 PHP
解决PHP程序运行时:Fatal error: Maximum execution time of 30 seconds exceeded in的错误提示
2016/11/25 PHP
PHP使用DOM和simplexml读取xml文档的方法示例
2017/02/08 PHP
PHP7中I/O模型内核剖析详解
2019/04/14 PHP
解决php用mysql方式连接数据库出现Deprecated报错问题
2019/12/25 PHP
js中将多个语句写成一个语句的两种方法小结
2007/12/08 Javascript
让Firefox支持event对象实现代码
2009/11/07 Javascript
Javascript让DEDECMS告别手写Tag
2014/09/01 Javascript
JavaScript中的类数组对象介绍
2014/12/30 Javascript
js动态创建及移除div的方法
2015/06/03 Javascript
基于javascript简单实现对身份证校验
2021/01/25 Javascript
你真的了解BOM中的history对象吗
2017/02/13 Javascript
JS全角与半角转化实例(分享)
2017/07/04 Javascript
手把手教你搭建ES6的开发运行环境
2017/07/11 Javascript
Vue隐藏显示、只读实例代码
2018/07/18 Javascript
详解react阻止无效重渲染的多种方式
2018/12/11 Javascript
[42:11]TNC vs Pain 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/20 DOTA
[01:07:34]DOTA2-DPC中国联赛定级赛 RNG vs Aster BO3第二场 1月9日
2021/03/11 DOTA
[01:07:15]DOTA2-DPC中国联赛 正赛 DLG vs XG BO3 第二场 1月25日
2021/03/11 DOTA
初步理解Python进程的信号通讯
2015/04/09 Python
解决pycharm无法调用pip安装的包问题
2018/05/18 Python
django项目登录中使用图片验证码的实现方法
2019/08/15 Python
python全局变量引用与修改过程解析
2020/01/07 Python
python自定义函数def的应用详解
2020/06/03 Python
python3.7中安装paddleocr及paddlepaddle包的多种方法
2020/11/27 Python
Notino意大利:购买香水和化妆品
2018/11/14 全球购物
英国哈罗德园艺:Harrod Horticultural
2020/03/31 全球购物
急诊科护士自我鉴定
2013/10/14 职场文书
宣传活动总结范文
2014/07/01 职场文书
关于国庆节的演讲稿
2014/09/05 职场文书
庆六一宣传标语
2014/10/08 职场文书
通知函格式范文
2015/04/27 职场文书
纯CSS实现酷炫的霓虹灯效果
2021/04/13 HTML / CSS
Keras在mnist上的CNN实践,并且自定义loss函数曲线图操作
2021/05/25 Python