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基础教程之获取本机ip数据包示例
Feb 10 Python
python实现同时给多个变量赋值的方法
Apr 30 Python
Python中列表的一些基本操作知识汇总
May 20 Python
python使用PyGame模块播放声音的方法
May 20 Python
详解Python3中的Sequence type的使用
Aug 01 Python
Python学习笔记之解析json的方法分析
Apr 21 Python
Python 快速实现CLI 应用程序的脚手架
Dec 05 Python
python中的turtle库函数简单使用教程
Jul 23 Python
Python调用Windows命令打印文件
Feb 07 Python
python中if及if-else如何使用
Jun 02 Python
python爬虫工具例举说明
Nov 30 Python
python实现跨年表白神器--你值得拥有
Jan 04 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发送有附件的电子邮件-(PHPMailer使用的实例分析)
2013/04/26 PHP
php 模拟 asp.net webFrom 按钮提交事件的思路及代码
2013/12/02 PHP
Drupal7 form表单二次开发要点与实例
2014/03/02 PHP
PDO操作MySQL的基础教程(推荐)
2017/08/18 PHP
PHP使用OB缓存实现静态化功能示例
2019/03/23 PHP
PHP程序员简单的开展服务治理架构操作详解(二)
2020/05/14 PHP
为jQuery.Treeview添加右键菜单的实现代码
2010/10/22 Javascript
jQuery代码优化 选择符篇
2011/11/01 Javascript
基于Bootstrap+jQuery.validate实现Form表单验证
2014/12/16 Javascript
JavaScript通过事件代理高亮显示表格行的方法
2015/05/27 Javascript
javascript实现根据3原色制作颜色选择器的方法
2015/07/17 Javascript
js获取元素的外链样式的简单实现方法
2016/06/06 Javascript
React-router中结合webpack实现按需加载实例
2017/05/25 Javascript
详解如何在vue项目中使用lodop打印插件
2018/09/27 Javascript
AngularJS 监听变量变化的实现方法
2018/10/09 Javascript
简单的React SSR服务器渲染实现
2018/12/11 Javascript
详解微信UnionID作用
2019/05/15 Javascript
利用Vue-draggable组件实现Vue项目中表格内容的拖拽排序
2019/06/07 Javascript
使用layui 的layedit定义自己的toolbar方法
2019/09/18 Javascript
layui点击按钮页面会自动刷新的解决方案
2019/10/25 Javascript
Django在Win7下的安装及创建项目hello word简明教程
2014/07/14 Python
Python爬虫辅助利器PyQuery模块的安装使用攻略
2016/04/24 Python
python去除字符串中的换行符
2017/10/11 Python
Python+OpenCV实现将图像转换为二进制格式
2020/01/09 Python
英国在线滑雪板和冲浪商店:The Board Basement
2020/01/11 全球购物
投标单位介绍信
2014/01/09 职场文书
九年级政治教学反思
2014/02/06 职场文书
求职自荐信的格式
2014/04/07 职场文书
婚前保证书
2014/04/29 职场文书
个人对照检查材料思想汇报
2014/09/26 职场文书
2015年超市员工工作总结
2015/05/04 职场文书
英语导游欢迎词
2015/09/30 职场文书
Pytest实现setup和teardown的详细使用详解
2021/04/17 Python
使用nginx配置访问wgcloud的方法
2021/06/26 Servers
Axios代理配置及封装响应拦截处理方式
2022/04/07 Vue.js
Python读取和写入Excel数据
2022/04/20 Python