数据结构与算法(Python)第四天

  • 链表
    • 双向链表
      • 操作
      • 实现
    • 单向循环链表
      • 操作
      • 实现
    • 栈结构实现
      • 操作
      • 实现
  • 队列
    • 队列的实现
      • 操作
      • 实现
    • 双端队列
      • 操作
      • 实现

链表

双向链表

一种更复杂的链表是“双向链表”或“双面链表”。每个节点有两个链接:一个指向前一个节点,当此节点为第一个节点时,指向空值;而另一个指向下一个节点,当此节点为最后一个节点时,指向空值。

双向链表操作示意图:

操作

  • is_empty() 链表是否为空
  • length() 链表长度
  • travel() 遍历链表
  • add(item) 链表头部添加
  • append(item) 链表尾部添加
  • insert(pos, item) 指定位置添加
  • remove(item) 删除节点
  • search(item) 查找节点是否存在

实现

# coding:utf-8class Node(object):"""定义节点"""def __init__(self,item):self.item=itemself.next=Noneself.prev=Noneclass DoubleLinkList(object):"""双链表"""def __init__(self,node=None):self.__head=nodedef is_empty(self):"""判断链表是否为空"""return self.__head == Nonedef length(self):"""链表长度"""# cur初始时指向头节点cur=self.__headcount=0# 尾节点指向None,当未到达尾部时while cur !=None:count +=1# 将cur后移一个节点cur= cur.nextreturn countdef travel(self):"""遍历整个链表"""cur=self.__headwhile cur != None:print(cur.item,end=" "),cur=cur.nextprint(end="\n")def add(self,item):"""链表头部添加元素,头插法"""node=Node(item)node.next=self.__headself.__head=nodenode.next.prev=nodedef append(self,item):"""链表尾部添加元素,尾插法"""node=Node(item)# 先判断链表是否为空,若是空链表,则将_head指向新节点if self.is_empty():self.__head=node# 若不为空,则找到尾部,将尾节点的next指向新节点else:cur=self.__headwhile cur.next !=None:cur=cur.nextcur.next=nodenode.prev=curdef insert(self,pos, item):"""指定位置添加元素:param pos 从0开始"""if pos<=0:self.add(item)elif pos>self.length()-1:self.append(item)else:cur= self.__headcount=0while count < pos:count += 1cur=cur.next#当循环退出后,cur指向pos的位置node=Node(item)node.next=curnode.prev=cur.prevcur.prev.next=nodecur.prev=nodedef remove(self,item):"""删除节点"""cur=self.__headwhile cur!=None:if cur.item == item:#先判断此节点是否为头节点#头节点if cur==self.__head:self.__head=cur.nextif cur.next:#判断链表是否只有一个节点cur.next.prev=Noneelse:cur.prev.next = cur.nextif cur.next:cur.next.prev=cur.prevbreakelse:cur=cur.nextdef search(self,item):"""查找节点是否存在"""cur=self.__headwhile cur !=None:if cur.item == item:return Trueelse:cur=cur.nextreturn Falseif __name__=="__main__":ll=DoubleLinkList()print(ll.is_empty())print(ll.length())ll.append(1)print(ll.is_empty())print(ll.length())ll.append(2)ll.add(8)ll.append(3)ll.append(4)ll.append(5)ll.append(6)ll.travel()ll.insert(-1,100) #100,8,1,2,3,4,5,6ll.travel()ll.insert(3,200)  #100,8,1,200,2,3,4,5,6ll.travel()ll.insert(10,300) #100,8,1,200,2,3,4,5,6,300ll.travel()ll.remove(200)ll.travel()ll.remove(100)ll.travel()ll.remove(300)ll.travel()

运行结果:

C:\ANACONDA\python.exe "C:/Users/Lenovo/PycharmProjects/Python data structure and algorithm-02/04_double_link_list.py"
True
0
False
1
8 1 2 3 4 5 6
100 8 1 2 3 4 5 6
100 8 1 200 2 3 4 5 6
100 8 1 200 2 3 4 5 6 300
100 8 1 2 3 4 5 6 300
8 1 2 3 4 5 6 300
8 1 2 3 4 5 6 Process finished with exit code 0

单向循环链表

单链表的一个变形是单向循环链表,链表中最后一个节点的next域不再为None,而是指向链表的头节点。


单向循环链表操作示意图:

操作

  • is_empty() 判断链表是否为空
  • length() 返回链表的长度
  • travel() 遍历
  • add(item) 在头部添加一个节点
  • append(item) 在尾部添加一个节点
  • insert(pos, item) 在指定位置pos添加节点
  • remove(item)删除一个节点
  • search(item) 查找节点是否存在

实现

# coding:utf-8#节点实现
class Node(object):"""节点构造"""def __init__(self,item):#_item存放数据元素self.item=item#_next是下一节点的标识self.next=None#单向循环链表的操作class SingleCycleLinkList(object):"""单向循环链表"""def __init__(self,node=None):self.__head=node#没进入这部分是一个空的单向循环链表if node:node.next=nodedef is_empty(self):"""判断链表是否为空"""return self.__head == Nonedef length(self):"""链表长度"""if self.is_empty():return 0# cur初始时指向头节点,用来移动遍历节点cur=self.__head#count用来记录数量count=1# 尾节点指向None,当未到达尾部时while cur.next !=self.__head:count +=1# 将cur后移一个节点cur= cur.nextreturn countdef travel(self):if self.is_empty():return"""遍历整个链表"""cur=self.__headwhile cur.next != self.__head:print(cur.item,end=" "),cur=cur.next#退出循环,cur指向尾节点,但尾节点的元素未打印print(cur.item)def add(self,item):"""链表头部添加元素,头插法"""node=Node(item)if self.is_empty():self.__head=nodenode.next=nodeelse:cur=self.__headwhile cur.next!=self.__head:cur=cur.next#退出循环时,cur指向尾节点node.next=self.__headself.__head=nodecur.next=self.__headdef append(self,item):"""链表尾部添加元素,尾插法"""node=Node(item)# 先判断链表是否为空,若是空链表,则将_head指向新节点if self.is_empty():self.__head=nodenode.next = node# 若不为空,则找到尾部,将尾节点的next指向新节点else:cur=self.__headwhile cur.next !=self.__head:cur=cur.nextnode.next=self.__headcur.next = nodedef insert(self,pos, item):"""指定位置添加元素:param pos 从0开始"""if pos<=0:self.add(item)elif pos>self.length()-1:self.append(item)else:pre= self.__headcount=0while count < (pos-1):count += 1pre=pre.next#当循环退出后,pre指向pos-1的位置node=Node(item)node.next=pre.nextpre.next=nodedef remove(self,item):"""删除节点"""if self.is_empty():returncur=self.__headpre=Nonewhile cur.next!=self.__head:if cur.item == item:#先判断此节点是否为头节点if cur==self.__head:# 头节点的情况# 找尾节点rear=self.__headwhile rear.next!=self.__head:rear=rear.nextself.__head=cur.nextrear.next=self.__headelse:# 中间节点pre.next=cur.nextreturnelse:pre=curcur=cur.next# 退出循环时,cur指向尾节点if cur.item==item:if cur==self.__head:#链表只有一个节点self.__head=Noneelse:pre.next=cur.nextdef search(self,item):"""查找节点是否存在"""if self.is_empty():return Falsecur=self.__headwhile cur.next !=self.__head:if cur.item == item:return Trueelse:cur=cur.next# 退出循环时,cur指向尾节点if cur.item==item:return Truereturn Falseif __name__=="__main__":ll=SingleCycleLinkList()print(ll.is_empty())print(ll.length())ll.append(1)print(ll.is_empty())print(ll.length())ll.append(2)ll.add(8)ll.append(3)ll.append(4)ll.append(5)ll.append(6)ll.travel()ll.insert(-1,100) #100,8,1,2,3,4,5,6ll.travel()ll.insert(3,200)  #100,8,1,200,2,3,4,5,6ll.travel()ll.insert(10,300) #100,8,1,200,2,3,4,5,6,300ll.travel()ll.remove(200)ll.travel()ll.remove(100)ll.travel()ll.remove(300)ll.travel()

运行结果:

C:\ANACONDA\python.exe "C:/Users/Lenovo/PycharmProjects/Python data structure and algorithm-02/05_single_cycle_link_list.py"
True
0
False
1
8 1 2 3 4 5 6
100 8 1 2 3 4 5 6
100 8 1 200 2 3 4 5 6
100 8 1 200 2 3 4 5 6 300
100 8 1 2 3 4 5 6 300
8 1 2 3 4 5 6 300
8 1 2 3 4 5 6Process finished with exit code 0

栈(stack),有些地方称为堆栈,是一种容器,可存入数据元素、访问元素、删除元素,它的特点在于只能允许在容器的一端(称为栈顶端指标,英语:top)进行加入数据(英语:push)和输出数据(英语:pop)的运算。没有了位置概念,保证任何时候可以访问、删除的元素都是此前最后存入的那个元素,确定了一种默认的访问顺序。

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

栈结构实现

栈可以用顺序表实现,也可以用链表实现。

操作

  • Stack() 创建一个新的空栈
  • push(item) 添加一个新的元素
  • item到栈顶
  • pop() 弹出栈顶元素
  • peek()返回栈顶元素
  • is_empty() 判断栈是否为空
  • size() 返回栈的元素个数

实现

# coding:utf-8class Stack(object):"""栈"""def __init__(self):self.__list=[]def push(self,item):"""添加一个新的元素item到栈顶"""self.__list.append(item)def pop(self):"""弹出栈顶元素"""return self.__list.pop()def peek(self):"""返回栈顶元素"""if self.__list:return self.__list[-1]else:return Nonedef is_empty(self):"""判断栈是否为空"""return self.__list==[]# return not self.__list  两句话一样的效果def size(self):"""返回栈的元素个数"""return len(self.__list)if __name__=="__main__":s=Stack()s.push(1)s.push(2)s.push(3)s.push(4)print(s)print(s.size())print(s.pop())print(s.pop())print(s.pop())print(s.pop())

运行结果:

C:\ANACONDA\python.exe "C:/Users/Lenovo/PycharmProjects/Python data structure and algorithm-02/06_stack.py"
<__main__.Stack object at 0x0000021AED807C48>
4
4
3
2
1Process finished with exit code 0

队列

队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。

队列是一种先进先出的(First In First Out)的线性表,简称FIFO。允许插入的一端为队尾,允许删除的一端为队头。队列不允许在中间部位进行操作!假设队列是q=(a1,a2,……,an),那么a1就是队头元素,而an是队尾元素。这样我们就可以删除时,总是从a1开始,而插入时,总是在队列最后。这也比较符合我们通常生活中的习惯,排在第一个的优先出列,最后来的当然排在队伍最后。

队列的实现

同栈一样,队列也可以用顺序表或者链表实现。

操作

  • Queue() 创建一个空的队列
  • enqueue(item) 往队列中添加一个item元素
  • dequeue() 从队列头部删除一个元素
  • is_empty() 判断一个队列是否为空 size() 返回队列的大小

实现

# coding=utf-8class Queue(object):"""队列"""def __init__(self):self.__list=[]def enqueue(self,item):"""往队列中添加一个item元素"""self.__list.append(item)def dequeue(self):"""从队列头部删除一个元素"""return self.__list.pop(0)def is_empty(self):"""判断一个队列是否为空"""return self.__list==[]def size(self):"""返回队列的大小"""return len(self.__list)if __name__=="__main__":s=Queue()s.enqueue(1)s.enqueue(2)s.enqueue(3)s.enqueue(4)print(s)print(s.size())print(s.dequeue())print(s.dequeue())print(s.dequeue())print(s.dequeue())

运行结果:

C:\ANACONDA\python.exe "C:/Users/Lenovo/PycharmProjects/Python data structure and algorithm-02/07_queue.py"
<__main__.Queue object at 0x00000261C03E1F08>
4
1
2
3
4Process finished with exit code 0

双端队列

双端队列(deque,全名double-ended queue),是一种具有队列和栈的性质的数据结构。

双端队列中的元素可以从两端弹出,其限定插入和删除操作在表的两端进行。双端队列可以在队列任意一端入队和出队。

操作

Deque() 创建一个空的双端队列
add_front(item) 从队头加入一个item元素
add_rear(item) 从队尾加入一个item元素
remove_front() 从队头删除一个item元素
remove_rear() 从队尾删除一个item元素
is_empty() 判断双端队列是否为空
size() 返回队列的大小

实现

# coding=utf-8class Deque(object):"""双端队列"""def __init__(self):self.__list = []def add_front(self,item):"""从队头加入一个item元素"""self.__list.insert(0,item)def add_rear(self,item):"""从队尾加入一个item元素"""self.__list.append(item)def remove_front(self) :"""从队头删除一个item元素"""return self.__list.pop(0)def remove_rear(self) :"""从队头删除一个item元素"""return self.__list.pop()def is_empty(self):"""判断一个队列是否为空"""return self.__list == []def size(self):"""返回队列的大小"""return len(self.__list)if __name__ == "__main__":s = Deque()s.add_front(1)s.add_rear(2)s.add_front(3)s.add_rear(4)print(s)print(s.size())print(s.remove_front())print(s.remove_rear())print(s.remove_front())print(s.remove_rear())

运行结果:

C:\ANACONDA\python.exe "C:/Users/Lenovo/PycharmProjects/Python data structure and algorithm-02/08_deque.py"
<__main__.Deque object at 0x0000023F3F12B748>
4
3
4
1
2Process finished with exit code 0

数据结构与算法(Python)第四天相关推荐

  1. 数据结构与算法(Python版)四十八:树的应用(表达式解析)

    树的应用:解析树(语法树) 将树用于表示语言中句子, 可以分析句子的各种语法成分, 对句子的各种成分进行处理 语法分析树主谓宾,定状补 程序设计语言的编译 词法.语法检查从语法树生成目标代码 自然语言 ...

  2. 数据结构与算法python语言实现-第四章答案

    数据结构与算法python语言实现-第四章答案 4.1 def findmax(S, index=0):if index == len(S) - 1:return S[index]max=findma ...

  3. 《数据结构与算法 Python语言描述》 读书笔记

    已经发布博客 <数据结构与算法 Python语言描述> 读书笔记 第二章 抽象数据类型和Python类 2.1 抽象数据类型abstract data type:ADT 2.1.1 使用编 ...

  4. 数据结构python课后答案_数据结构与算法:Python语言描述 1~5章课后习题

    数据结构与算法:Python语言描述 1~5章课后习题 发布时间:2018-07-19 20:42, 浏览次数:1885 , 标签: Python MarkDown语法写的,不知道为啥上传到CSDN不 ...

  5. mooc数据结构与算法python版期末考试_数据结构与算法Python版-中国大学mooc-试题题目及答案...

    数据结构与算法Python版-中国大学mooc-试题题目及答案 更多相关问题 婴儿出生一两天后就有笑的反应,这种笑的反应属于(). [判断题]填制原始凭证,汉字大写金额数字一律用正楷或草书书写,汉字大 ...

  6. python数据结构算法 北京大学_北京大学公开课《数据结构与算法Python版》

    之前我分享过一个数据结构与算法的课程,很多小伙伴私信我问有没有Python版. 看了一些公开课后,今天特向大家推荐北京大学的这门课程:<数据结构与算法Python版>. 课程概述 很多同学 ...

  7. 数据结构与算法python描述_数据结构与算法——Python语言描述.pdf

    数据结构与算法--Python语言描述.pdf 欢迎加入非盈利Python编学习交流程QQ群783462347,群里免费提供500+本Python书籍! 欢迎加入非盈利Python编程学习交流程QQ群 ...

  8. 数据结构与算法 python版 之 递归三定律

    #数据结构与算法 python版 之 谢尔宾斯基三角形 , 树叉 1.为了向阿西莫夫的"机器人三定律"直径,递归算法也总结出"三定律" 1递归算法必须有一个基本 ...

  9. 《数据结构与算法 Python语言实现》书评与学习心得

    做为Python小白,本人几个月前读完了Mark Lutz的1400页巨著<Learning Python>(太TM啰嗦了,读过的请举手),本打算继续学习下一步<Programmin ...

  10. 数据结构python版 答案,中国大学 MOOC_数据结构与算法Python版_章节测验答案

    中国大学 MOOC_数据结构与算法Python版_章节测验答案 更多相关问题 认识的本质是()A.肯定世界是可知的B.主体对客体的能动反映C.主体对客体的直观反映D.实践是 水灰比是影响混凝土()的主 ...

最新文章

  1. python同步打乱
  2. [005] .NET 的执行模型
  3. 数据库基础系列之一:MySQL账户
  4. 用flask部署模型
  5. mysql面试考点_mysql面试知识点
  6. 11.Axis客户端接收不同参数类型
  7. 一个光标绘制问题的解决过程
  8. 协创物联网合肥产业园项目远程预付费电能管理系统的设计与应用
  9. 项目管理 计算机仿真,刘宝林老师【项目管理】《挑战埃及》沙盘课程内容分享...
  10. ESET ESS 激活码
  11. 超全地牢场景unity3d模型素材网站整理
  12. 矩阵A的值域空间和其零空间
  13. 游戏服务器是干什么的(大话、浅析)
  14. html5数学公式编辑器,Daum Equation Editor:数学公式编辑器
  15. lisp ssget 浩辰_lisp程序--AutoCAD和浩辰GstarCAD.pdf
  16. 大三下,我们该做什么?一篇被转万次的日志,你值得一看
  17. WIFI关键器件选型
  18. 20189200余超 2018-2019-2 移动平台应用开发实践第三周作业
  19. 将React Native 集成进现有OC项目中(过程记录) 、jsCodeLocation 生成方式总结
  20. 震灾哀悼期间网页变黑白色调的小技巧

热门文章

  1. 【codevs3119】高精度开根号(二分答案)
  2. 【Luogu1616】疯狂的采药
  3. JSP→基本语法/静态内容/指令/动作/表达式/小脚本(Scriptlet)/声明/注释、JSP页面声明周期、代码样例、九大隐式内置对象及方法代码样例
  4. 设置层级为2html,前端知识(Css)汇总2
  5. rsa 公 填充模式的_RSA加密的填充模式
  6. 们--加强菲波那切数列
  7. jquery赋值节点
  8. docker 容器和镜像的区别
  9. 2017百度之星资格赛:1001. 度度熊保护村庄(floyd最小环)
  10. 51nod-1366:贫富差距