一、栈
栈是由一系列对象组合成的一个集合,这些对象的插入和删除操作遵循后进先出(LIFO)的原则。用户可以在任何时刻向栈中插入一个对象,但只能取得或者删除最后一个插入的对象(即所谓的栈顶)。
图片来源:https://www.cnblogs.com/silence-cho/p/10029562.html
class ArrayStack():
"""
LIFO Stack implenmentation a Python list as underlying storage
"""
def __init__(self):
"""
Create an empty stack
"""
self._data = []
def __len__(self):
"""
Return the number of elements in the stack
:return: number of elements
"""
return len(self._data)
def is_empty(self):
"""
Return True if the stack is empty
:return:
"""
return len(self._data) == 0
def push(self, e):
"""
Add element e to the top of stack
:param e: value
:return: None
"""
self._data.append(e)
def top(self):
"""
Return(but not remove)the element at the top of the stack
Raise Empty exception if the stack is empty
:return: value
"""
if self.is_empty():
raise Empty("Stack is empty")
return self._data[-1]
def pop(self):
"""
Remove and return the element from the top of the stack
Raise Empty exception if the stack is empty
:return: value
"""
if self.is_empty():
raise Empty("Stack is empty")
return self._data.pop()
@property
def data(self):
return self._data
def Empty(Exception):
"""
Error attention to access an element form an empty container.
:param Exception:
:return:
"""
pass
二、使用环形数组实现队列
队列是另一种基本的数据结构,它与栈互为“表亲”关系,队列是由一系列对象组成的集合,这些对象的插入和删除遵循先进先出(First in First out, FIFO)的原则。也就是说,元素可以在任何时刻进行插入,但是只有处在队列最前面的元素才能被删除。
使用环形数组:为了开发一种更加健壮(Robust)的队列实现方法,我们让队列的前端趋向右端,并且让队列内的元素在底层数组的尾部“循环”。假定底层数组的长度为固定值N,它比实际队列中元素的数量大,新的元素在当前队列的尾部利用入队列操作进入队列,逐步将元素从队列的前面插入索引为N-1的位置,然后紧接着是索引为0的位置(此时该位置上的元素应已被pop()出去),接下来是索引为1的位置。同时,为了让空间不被浪费,我们可以动态调整数组的容量,当数组中元素个数超过数组容量时,我们将数组的容量扩大到原来的两倍,当数组中的元素个数少于数组容量的1/4时,我们便将数组容量缩小为原来的一半。
如下图:头部所在的数组索引为12,尾部所在的数组索引为3。
class ArrayQueue:
"""
FIFO queue implementation using Python list as underlying storage
"""
DEFAULT_CAPACITY = 5 # moderate capacity for all new queues
def __init__(self):
"""
Create an empty queue
"""
self._data = [None] * ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""
Return the number of elements in the queue.
:return:
"""
return self._size
def is_empty(self):
"""
Return True if the queue is empty
:return:
"""
return self._size == 0
def first(self):
"""
Return (but not remove) the element at the front of the queue
Raise Empty exception if the queue is empty
:return:
"""
if self.is_empty():
raise Empty("Queue is empty")
return self._data(self._front)
def dequeue(self):
"""
Remove and return the first element of the queue
Raise Empty exception if the queue is empty
:return:
"""
if self.is_empty():
raise Empty("Queue is empty")
answer = self._data[self._front]
self._data[self._front] = None # help garbage collection
self._front = (self._front + 1) % len(self._data)
self._size -= 1
# if the number of elements is less than 1/4 of the array
# capacity, reduce the size of the array
if 0 < self._size < len(self._data) // 4:
self._resize(len(self._data) // 2)
return answer
def enqueue(self, e):
"""
Add an element to the back of queue
:param e:
:return:
"""
if self._size == len(self._data):
self._resize(2 * len(self._data)) # double the array size
avail = (self._front + self._size) % len(self._data)
self._data[avail] = e
self._size += 1
def _resize(self, cap):
"""
Resize to a new list of capacity >= len(self)
:param cap:
:return:
"""
old = self._data
self._data = [None] * cap
walk = self._front
for k in range(self._size):
self._data[k] = old[walk]
walk = (1 + walk) % len(old)
self._front = 0
def show(self):
"""
Show queue from front to back
:return:
"""
ls = []
walk = self._front
for k in range(self._size):
ls.append(self._data[walk])
walk = walk = (1 + walk) % len(self._data)
return ls
三、使用环形数组实现双端队列
假定我们实例化了一个双端数组D,这个实例支持如下方法:
D.add_first():向双端队列的前面添加一个元素e
D.add_last():在双端队列的后面添加一个元素e
D.delete_first():在双端队列中移除并返回第一个元素,若双端队列为空,则触发一个错误
D.delete_last():从双端队列中移除并返回最后一个元素,若双端队列为空,则触发一个错误
D.first():返回(但不移除)双端队列的第一个元素,若双端队列为空,则触发一个错误
D.last():返回(但不移除)双端队列的最后一个元素,若双端队列为空,则触发一个错误
D.is_empty():如果双端队列不包括任何一个元素,则返回布尔值“True”
len(D):返回当前双端队列中的元素个数,在python中,我们用__len__这个特殊的方法实现
此类继承了单端队列的类:
class Deque(ArrayQueue):
def __init__(self):
super(Deque, self).__init__()
self._back = 0
def add_first(self, e):
"""
Add an element to the front of double-ended queue
:return:
"""
if self._size == len(self._data):
self._resize(2 * len(self._data)) # double the array size
avail = (self._front - 1) % len(self._data) #
self._data[avail] = e
self._front = (self._front - 1) % len(self._data)
self._size += 1
def add_last(self, e):
"""
Add an element to the behind of double-ended queue
:param e:
:return:
"""
self.enqueue(e)
def delete_first(self):
"""
Remove an element to the front of double-ended queue and return the element
:return:
"""
return self.dequeue()
def delete_last(self):
"""
Remove an element to the behind of double-ended queue and return the element
:return:
"""
self._back = (self._front + self._size - 1) % len(self._data)
if self.is_empty():
raise Empty("Queue is empty")
answer = self._data[self._back]
self._data[self._back] = None # help garbage collection
self._size -= 1
# if the number of elements is less than 1/4 of the array
# capacity, reduce the size of the array
if 0 < self._size < len(self._data) // 4:
self._resize(len(self._data) // 2)
return answer
def first(self):
"""
Return the first element in the double-ended queue
raise Empty exception if the double-ended queue is empty
:return:
"""
if self.is_empty():
raise Empty("Queue is empty")
return self._data[self._front]
def last(self):
"""
Return the last element in the double-ended queue
raise Empty exception if the double-ended queue is empty
:return:
"""
self._back = (self._front + self._size - 1) % len(self._data)
if self.is_empty():
raise Empty("Queue is empty")
return self._data[self._back]
四、Python中自带的双端队列
Python的标准collections模块中包含对一个双端列表的实现方法。继续实例化D。
len(D):元素数量
D.appendleft():加到开头
D,append():加到结尾
D.popleft():从开头移除
D.pop():从结尾移除
D[0]:访问第一个元素
D[-1]:访问最后一个元素
D[j]:通过索引访问其中任何一项
D[j]=val:通过索引修改任意一项
D.clear():清除所有内容
D.rotate(k):循环右移k步
D.remove(e):移除第一个匹配的元素
D.count(e):统计对于e匹配的数量
import collections
D = collections.deque()