# -*- coding: utf-8 -*-

from collections import deque

class Node(object):
def __init__(self, value=None, next=None):
self.value = value
self.next = next def __str__(self):
return '<Node: value: {}, next={}>'.format(self.value, self.next) __repr__ = __str__ class LinkedList(object):
""" 链接表 ADT
[root] -> [node0] -> [node1] -> [node2]
""" def __init__(self, maxsize=None):
"""
:param maxsize: int or None, 如果是 None,无限扩充
"""
self.maxsize = maxsize
self.root = Node() # 默认 root 节点指向 None
self.tailnode = None
self.length = 0 def __len__(self):
return self.length def append(self, value): # O(1)
if self.maxsize is not None and len(self) >= self.maxsize:
raise Exception('LinkedList is Full')
node = Node(value)
tailnode = self.tailnode
if tailnode is None:
self.root.next = node
else:
tailnode.next = node
self.tailnode = node
self.length += 1 def appendleft(self, value):
headnode = self.root.next
node = Node(value)
self.root.next = node
node.next = headnode
self.length += 1 def __iter__(self):
for node in self.iter_node():
yield node.value def iter_node(self):
"""遍历 从 head 节点到 tail 节点"""
curnode = self.root.next
while curnode is not self.tailnode: # 从第一个节点开始遍历
yield curnode
curnode = curnode.next # 移动到下一个节点
yield curnode def remove(self, value): # O(n)
""" 删除包含值的一个节点,将其前一个节点的 next 指向被查询节点的下一个即可 :param value:
"""
prevnode = self.root #
curnode = self.root.next
for curnode in self.iter_node():
if curnode.value == value:
prevnode.next = curnode.next
del curnode
self.length -= 1
return 1 # 表明删除成功
else:
prevnode = curnode
return -1 # 表明删除失败 def find(self, value): # O(n)
""" 查找一个节点,返回序号,从 0 开始 :param value:
"""
index = 0
for node in self.iter_node(): # 我们定义了 __iter__,这里就可以用 for 遍历它了
if node.value == value:
return index
index += 1
return -1 # 没找到 def popleft(self): # O(1)
""" 删除第一个链表节点
"""
if self.root.next is None:
raise Exception('pop from empty LinkedList')
headnode = self.root.next
self.root.next = headnode.next
self.length -= 1
value = headnode.value
del headnode
return value def clear(self):
for node in self.iter_node():
del node
self.root.next = None
self.length = 0 class EmptyError(Exception):
"""自定义异常"""
pass class Queue(object):
def __init__(self, maxsize=None):
self.maxsize = maxsize
self._item_link_list = LinkedList() def __len__(self):
return len(self._item_link_list) def push(self, value): # O(1)
""" 队尾添加元素 """
return self._item_link_list.append(value) def pop(self):
"""队列头部删除元素"""
if len(self) <= 0:
raise EmptyError('empty queue')
return self._item_link_list.popleft() def test_queue():
q = Queue()
q.push(0)
q.push(1)
q.push(2) assert len(q) == 3 assert q.pop() == 0
assert q.pop() == 1
assert q.pop() == 2 import pytest # pip install pytest
with pytest.raises(EmptyError) as excinfo:
q.pop()
assert 'empty queue' == str(excinfo.value) class MyQueue:
"""
使用 collections.deque 可以迅速实现一个队列
"""
def __init__(self):
self.items = deque() def append(self, val):
return self.items.append(val) def pop(self):
return self.items.popleft() def __len__(self):
return len(self.items) def empty(self):
return len(self.items) == 0 def front(self):
return self.items[0]

链表实现队列(python)的更多相关文章

  1. Java数据结构——用双端链表实现队列

    //================================================= // File Name : LinkQueue_demo //---------------- ...

  2. 教你如何使用Java手写一个基于链表的队列

    在上一篇博客[教你如何使用Java手写一个基于数组的队列]中已经介绍了队列,以及Java语言中对队列的实现,对队列不是很了解的可以我上一篇文章.那么,现在就直接进入主题吧. 这篇博客主要讲解的是如何使 ...

  3. 第二百九十二节,RabbitMQ多设备消息队列-Python开发

    RabbitMQ多设备消息队列-Python开发 首先安装Python开发连接RabbitMQ的API,pika模块 pika模块为第三方模块  对于RabbitMQ来说,生产和消费不再针对内存里的一 ...

  4. 使用python实现数组、链表、队列、栈

    引言 什么是数据结构? 数据结构是指相互之间存在着一种或多种关系的数据元素的集合和该集合中数据元素之间的关系组成. 简单来说,数据结构就是设计数据以何种方式组织并存储在计算机中. 比如:列表,集合和字 ...

  5. 数据结构:栈 顺序表方法和单链表方法(python版)

    #!/usr/bin/env python # -*- coding:utf-8 -*- class StackUnderflow(ValueError): pass #链表节点 class Node ...

  6. 【原创】C++链表如何像Python List一样支持多种数据类型

    用过Python的码友都知道,Python中List支持多种数据类型,如下面代码所示链表li内的数据类型可以是整数,同时也可以是字符串,当然也可以是其他数据类型. 1: >>> li ...

  7. 利用 C++ 单向链表实现队列

    利用C++ 单向链表实现数据结构队列,其实和上一篇基本内容相同,仅仅是插入的时候在链表的尾部插入,取元素都是一样的,都从头部取. #pragma once #include "stdio.h ...

  8. chapter11_2 Lua链表与队列

    链表 由于table是动态的实体,所以在Lua中实现链表是很方便的.每个节点以一个table来表示,一个“链表”只是节点table中的一个字段. 该字段包含了对其他table的引用.例如,要实现一个基 ...

  9. 队列queue(2):链表实现队列

    基本概念 队列是只允许在一端进行插入操作,另一端进行删除操作的线性表. 我们规定,允许删除的叫做队首"head",允许插入的叫做队尾"tail". 基本操作 我 ...

随机推荐

  1. 12点睛Spring4.1-Spring Aware

    12.1 Aware 我们设计的准则是解耦,这就意味着我们不能对Spring的IoC容器有直接的依赖,但是我们还是想我们的bean能识别容器的资源; 使用aware能让我们在应用的任意位置获得spri ...

  2. The underlying connection was closed: The connection was closed unexpectedly.

    基础连接已经关闭: 连接被意外关闭. 基础连接已经关闭: 发送时发生错误 防火墙问题.或是杀毒软件,卫士之类的.(360 卸载 )

  3. Andrew Ng机器学习课程9

    Andrew Ng机器学习课程9 首先以一个工匠为例,说明要成为一个出色的工匠,就需要掌握各种工具的使用,才能知道在具体的任务中选择什么工具来做.所以今天要讲的就是机器学习的理论部分. bias va ...

  4. Andrew Ng机器学习课程7

    回顾 通过定义训练集S={(x(i),y(i));i=1,2,...,m}与线性决策平面(w,b)之间的function margin γ^和geometric margin γ .好的分类决策平面特 ...

  5. .bashrc修改环境变量文件后ls之类的不能用了

    在命令行中输入 export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/X11R6/bin之后在修改回来

  6. pandas对时间列分组求diff遇到的问题

    例子: df = pd.DataFrame() df['A'] = [1, 1, 2] df['B'] = [datetime.date(2018, 1, 2), datetime.date(2018 ...

  7. CentOS 安装tab命令补全

    CentOS 安装tab命令补全 1. 安装epel 源 yum -y install epel-release 2. 加快yum速度 yum -y install yum-plugin-fastes ...

  8. linux 编程 如何判断socket断开???--ongoing

    1 利用select ? 2从github上找例子 3 学习asio  c++ library

  9. Linux查看库依赖方法

    1.查看依赖的库:objdump -x xxx.so | grep NEEDED 2.查看可执行程序依赖的库:objdump -x 可执行程序名 | grep NEEDED 3.查看缺少的库: ldd ...

  10. Java中的事务及使用

    什么是事务? 事务(Transaction),一般是指要做的或所做的事情.在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元(unit).事务通常由高级数据库操纵语言或编程语言(如S ...