Python实现基本线性数据结构


Posted in Python onAugust 22, 2016

数组

数组的设计

数组设计之初是在形式上依赖内存分配而成的,所以必须在使用前预先请求空间。这使得数组有以下特性:

     1、请求空间以后大小固定,不能再改变(数据溢出问题);

     2、在内存中有空间连续性的表现,中间不会存在其他程序需要调用的数据,为此数组的专用内存空间;

     3、在旧式编程语言中(如有中阶语言之称的C),程序不会对数组的操作做下界判断,也就有潜在的越界操作的风险(比如会把数据写在运行中程序需要调用的核心部分的内存上)。

因为简单数组强烈倚赖电脑硬件之内存,所以不适用于现代的程序设计。欲使用可变大小、硬件无关性的数据类型,Java等程序设计语言均提供了更高级的数据结构:ArrayListVector等动态数组。

Python的数组

从严格意义上来说:Python里没有严格意义上的数组。

List可以说是Python里的数组,下面这段代码是CPython的实现List的结构体:

typedef struct {
 PyObject_VAR_HEAD
 /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
 PyObject **ob_item;

 /* ob_item contains space for 'allocated' elements. The number
  * currently in use is ob_size.
  * Invariants:
  *  0 <= ob_size <= allocated
  *  len(list) == ob_size
  *  ob_item == NULL implies ob_size == allocated == 0
  * list.sort() temporarily sets allocated to -1 to detect mutations.
  *
  * Items must normally not be NULL, except during construction when
  * the list is not yet visible outside the function that builds it.
  */
 Py_ssize_t allocated;
} PyListObject;

当然,在Python里它就是数组。
后面的一些结构也将用List来实现。

堆栈

什么是堆栈

堆栈(英语:stack),也可直接称栈,在计算机科学中,是一种特殊的串列形式的数据结构,它的特殊之处在于只能允许在链接串列或阵列的一端(称为堆叠顶端指标,英语:top)进行加入资料(英语:push)和输出资料(英语:pop)的运算。另外堆叠也可以用一维阵列或连结串列的形式来完成。堆叠的另外一个相对的操作方式称为伫列。

由于堆叠数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。

特点

     1、先入后出,后入先出。

     2、除头尾节点之外,每个元素有一个前驱,一个后继。

操作

从原理可知,对堆栈(栈)可以进行的操作有:

     1、top() :获取堆栈顶端对象

     2、push() :向栈里添加一个对象

     3、pop() :从栈里推出一个对象

实现

class my_stack(object):
 def __init__(self, value):
  self.value = value
  # 前驱
  self.before = None
  # 后继
  self.behind = None

 def __str__(self):
  return str(self.value)


def top(stack):
 if isinstance(stack, my_stack):
  if stack.behind is not None:
   return top(stack.behind)
  else:
   return stack


def push(stack, ele):
 push_ele = my_stack(ele)
 if isinstance(stack, my_stack):
  stack_top = top(stack)
  push_ele.before = stack_top
  push_ele.before.behind = push_ele
 else:
  raise Exception('不要乱扔东西进来好么')


def pop(stack):
 if isinstance(stack, my_stack):
  stack_top = top(stack)
  if stack_top.before is not None:
   stack_top.before.behind = None
   stack_top.behind = None
   return stack_top
  else:
   print('已经是栈顶了')

队列

什么是队列

和堆栈类似,唯一的区别是队列只能在队头进行出队操作,所以队列是是先进先出(FIFO, First-In-First-Out)的线性表

特点

      1、先入先出,后入后出

      2、除尾节点外,每个节点有一个后继

      3、(可选)除头节点外,每个节点有一个前驱

操作

      1、push() :入队

      2、pop() :出队

实现

普通队列

class MyQueue():
 def __init__(self, value=None):
  self.value = value
  # 前驱
  # self.before = None
  # 后继
  self.behind = None

 def __str__(self):
  if self.value is not None:
   return str(self.value)
  else:
   return 'None'


def create_queue():
 """仅有队头"""
 return MyQueue()


def last(queue):
 if isinstance(queue, MyQueue):
  if queue.behind is not None:
   return last(queue.behind)
  else:
   return queue


def push(queue, ele):
 if isinstance(queue, MyQueue):
  last_queue = last(queue)
  new_queue = MyQueue(ele)
  last_queue.behind = new_queue


def pop(queue):
 if queue.behind is not None:
  get_queue = queue.behind
  queue.behind = queue.behind.behind
  return get_queue
 else:
  print('队列里已经没有元素了')

def print_queue(queue):
 print(queue)
 if queue.behind is not None:
  print_queue(queue.behind)

链表

什么是链表

链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里存到下一个节点的指针(Pointer)。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而顺序表相应的时间复杂度分别是O(logn)和O(1)。

特点

使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。

操作

      1、init() :初始化

      2、insert() : 插入

      3、trave() : 遍历

      4、delete() : 删除

      5、find() : 查找

实现

此处仅实现双向列表

class LinkedList():
 def __init__(self, value=None):
  self.value = value
  # 前驱
  self.before = None
  # 后继
  self.behind = None

 def __str__(self):
  if self.value is not None:
   return str(self.value)
  else:
   return 'None'


def init():
 return LinkedList('HEAD')


def delete(linked_list):
 if isinstance(linked_list, LinkedList):
  if linked_list.behind is not None:
   delete(linked_list.behind)
   linked_list.behind = None
   linked_list.before = None
  linked_list.value = None

总结

以上就是利用Python实现基本线性数据结构的全部内容,希望这篇文章对大家学习Python能有所帮助。如果有疑问可以留言讨论。

Python 相关文章推荐
采用python实现简单QQ单用户机器人的方法
Jul 03 Python
Python编写检测数据库SA用户的方法
Jul 11 Python
深入解析Python中的集合类型操作符
Aug 19 Python
python从入门到精通(DAY 1)
Dec 20 Python
基于Django模板中的数字自增(详解)
Sep 05 Python
flask入门之文件上传与邮件发送示例
Jul 18 Python
python抓取搜狗微信公众号文章
Apr 01 Python
DJango的创建和使用详解(默认数据库sqlite3)
Nov 18 Python
pytorch 改变tensor尺寸的实现
Jan 03 Python
pytorch实现对输入超过三通道的数据进行训练
Jan 15 Python
PyTorch中Tensor的数据类型和运算的使用
Sep 03 Python
pip 20.3 新版本发布!即将抛弃 Python 2.x(推荐)
Dec 16 Python
Python进行数据提取的方法总结
Aug 22 #Python
详解Python实现按任意键继续/退出的功能
Aug 19 #Python
利用Python开发微信支付的注意事项
Aug 19 #Python
Python用模块pytz来转换时区
Aug 19 #Python
教你用python3根据关键词爬取百度百科的内容
Aug 18 #Python
利用Python爬取可用的代理IP
Aug 18 #Python
总结用Pdb库调试Python的方式及常用的命令
Aug 18 #Python
You might like
php日历[测试通过]
2008/03/27 PHP
php数字游戏 计算24算法
2012/06/10 PHP
php数组(array)输出的三种形式详解
2013/06/05 PHP
linux下为php添加iconv模块的方法
2016/02/28 PHP
PHP  Yii清理缓存的实现方法
2016/11/10 PHP
javascript 极速 隐藏/显示万行表格列只需 60毫秒
2009/03/28 Javascript
jQuery EasyUI API 中文文档 - Form表单
2011/10/06 Javascript
javascript学习笔记(八)正则表达式
2014/10/08 Javascript
javascript实现table表格隔行变色的方法
2015/05/13 Javascript
JavaScript获取IP获取的是IPV6 如何校验
2016/06/12 Javascript
vue中$set的使用(结合在实际应用中遇到的坑)
2018/07/10 Javascript
Nodejs中使用puppeteer控制浏览器中视频播放功能
2019/08/26 NodeJs
微信小程序表单验证WxValidate的使用
2019/11/27 Javascript
JS typeof fn === 'function' &amp;&amp; fn()详解
2020/08/22 Javascript
vue自定义指令限制输入框输入值的步骤与完整代码
2020/08/30 Javascript
CentOS6.5设置Django开发环境
2016/10/13 Python
python3爬取淘宝信息代码分析
2018/02/10 Python
Python使用pickle模块报错EOFError Ran out of input的解决方法
2018/08/16 Python
python实现归并排序算法
2018/11/22 Python
关于python之字典的嵌套,递归调用方法
2019/01/21 Python
python爬虫项目设置一个中断重连的程序的实现
2019/07/26 Python
python ETL工具 pyetl
2020/06/07 Python
美国知名的旅游网站:OneTravel
2018/10/09 全球购物
如何利用XMLHTTP检测URL及探测服务器信息
2013/11/10 面试题
村官学习十八大感想
2014/01/15 职场文书
鲜果饮品店创业计划书
2014/01/21 职场文书
遵纪守法演讲稿
2014/05/23 职场文书
园林系毕业生求职信
2014/06/23 职场文书
党的群众路线教育实践活动个人整改方案
2014/09/21 职场文书
大学生档案自我鉴定(2篇)
2014/10/14 职场文书
群众路线调研报告范文
2014/11/03 职场文书
全陪导游词
2015/02/04 职场文书
公司中层管理培训心得体会
2016/01/11 职场文书
Python实战之用tkinter库做一个鼠标模拟点击器
2021/04/27 Python
python利用while求100内的整数和方式
2021/11/07 Python
Navicat Premium自定义 sql 标签的创建方式
2022/09/23 数据库