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 相关文章推荐
Python3使用requests包抓取并保存网页源码的方法
Mar 15 Python
启动targetcli时遇到错误解决办法
Oct 26 Python
Python内置模块logging用法实例分析
Feb 12 Python
python xlsxwriter创建excel图表的方法
Jun 11 Python
python读csv文件时指定行为表头或无表头的方法
Jun 26 Python
Python qqbot 实现qq机器人的示例代码
Jul 11 Python
python 随机森林算法及其优化详解
Jul 11 Python
用django设置session过期时间的方法解析
Aug 05 Python
PyTorch里面的torch.nn.Parameter()详解
Jan 03 Python
python实现引用其他路径包里面的模块
Mar 09 Python
python 实现全球IP归属地查询工具
Dec 18 Python
python 使用tkinter与messagebox写界面和弹窗
Mar 20 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 expects parameter 1 to be resource, array given 错误
2011/03/23 PHP
php中get_headers函数的作用及用法的详细介绍
2013/04/27 PHP
Linux下PHP安装mcrypt扩展模块笔记
2014/09/10 PHP
Yii框架在页面输出执行sql语句以方便调试的实现方法
2014/12/24 PHP
php绘制一条弧线的方法
2015/01/24 PHP
php实现的美国50个州选择列表实例
2015/04/20 PHP
深入分析PHP优化及注意事项
2016/07/04 PHP
thinkphp框架表单数组实现图片批量上传功能示例
2020/04/04 PHP
Jquery下判断Id是否存在的代码
2011/01/06 Javascript
自定义一个jquery插件[鼠标悬浮时候 出现说明label]
2011/06/27 Javascript
JS 修改URL参数(实现代码)
2013/07/08 Javascript
Jquery创建层显示标题和内容且随鼠标移动而移动
2014/01/26 Javascript
详细解读JavaScript的跨浏览器事件处理
2015/08/12 Javascript
javascript cookie用法基础教程(概念,设置,读取及删除)
2016/09/20 Javascript
深入理解JavaScript定时机制
2016/10/27 Javascript
thinkjs微信中控之微信鉴权登陆的实现代码
2019/08/08 Javascript
JS实现时间校验的代码
2020/05/25 Javascript
Python中Threading用法详解
2017/12/27 Python
python pandas 如何替换某列的一个值
2018/06/09 Python
在PyCharm中实现关闭一个死循环程序的方法
2018/11/29 Python
在Python运行时动态查看进程内部信息的方法
2019/02/22 Python
CentOS7安装Python3的教程详解
2019/04/10 Python
深入了解Django View(视图系统)
2019/07/23 Python
win10子系统python开发环境准备及kenlm和nltk的使用教程
2019/10/14 Python
Python散点图与折线图绘制过程解析
2019/11/30 Python
Python 随机生成测试数据的模块:faker基本使用方法详解
2020/04/09 Python
Tensorflow与Keras自适应使用显存方式
2020/06/22 Python
css3的动画特效之动画序列(animation)
2017/12/22 HTML / CSS
化工专业推荐信范文
2013/11/28 职场文书
创业计划书怎样才能打动风投
2014/01/01 职场文书
岳父生日宴会答谢词
2014/01/13 职场文书
服务生自我鉴定
2014/01/22 职场文书
护理职业生涯规划书
2014/01/24 职场文书
网管求职信
2014/03/03 职场文书
开展党的群众路线教育实践活动剖析材料
2014/10/13 职场文书
Elasticsearch6.2服务器升配后的bug(避坑指南)
2022/09/23 Servers