python 栈和队列_python 栈和队列的基本实现
python中的列表結(jié)構(gòu)可以用來實現(xiàn)棧和隊列。
【棧】:
棧是一種數(shù)據(jù)結(jié)構(gòu),具有先入后出的特點,并且棧的所有操作只能在某一端進行,能進行操作的一端的第一個元素稱為棧頂,另一端的第一個元素稱為棧底
棧的五種基本方法:
push: 元素進棧
pop: 元素出棧,刪除棧頂元素,并返回該元素
isEmpty: 判斷棧是否為空;棧為空,返回True;棧不為空,返回False
peek: 訪問棧頂元素
length: 返回棧中元素的個數(shù)
1 classStack():2 def __init__(self):3 self.stack =[]4
5 defpush(self, data):6 self.stack.append(data)7
8 defpop(self):9 if notself.isEmpty():10 returnself.stack.pop()11 else:12 print('StackError: fail to pop, the stack is empty.')13
14 defisEmpty(self):15 return self.length() ==016
17 defpeek(self):18 if notself.isEmpty():19 return self.stack[-1]20 else:21 print("The stack is empty.")22
23 deflength(self):24 return len(self.stack)
【隊列】:
隊列是一種數(shù)據(jù)結(jié)構(gòu),具有先入先出的特點,元素的插入和刪除分別在不同的端進行,能夠插入元素的隊列一端稱為隊尾,另一端只能刪除元素,稱為隊首
隊列的五種基本操作:
push: 從隊尾插入元素
pop: 從隊首刪除元素
isEmpty: 判斷隊列是否為空
peek: 訪問隊首元素
length: 獲取隊列中元素個數(shù)
1 classQueue():2 def __init__(self):3 self.queue =[]4
5 defpush(self, data):6 self.queue.append(data)7
8 defpop(self):9 if notself.isEmpty():10 returnself.queue.pop(0)11 else:12 print('StackError: fail to pop, the stack is empty.')13
14 defisEmpty(self):15 return self.length() ==016
17 defpeek(self):18 if notself.isEmpty():19 returnself.queue[0]20 else:21 print("The queue is empty.")22
23 deflength(self):24 return len(self.queue)
【雙端隊列】:
deque模塊是Python標準庫collections中的一個內(nèi)置模塊,實現(xiàn)雙端隊列的功能,在隊列的兩端都可以進行插入和刪除
使用list存儲數(shù)據(jù)時,按索引訪問元素很快,但是插入和刪除元素就很慢了,因為list是線性存儲,數(shù)據(jù)量大的時候,插入和刪除效率很低。
deque是為了高效實現(xiàn)插入和刪除操作的雙向列表,適合用于隊列和棧:
deque的種基本操作:
append: 入隊,從隊列右端插入一個元素
appendleft: 入隊,從隊列左端刪除一個元素
extend: 迭代處理其輸入,對每個元素完成與append()相同的處理
extendleft: 迭代處理其輸入,對每個元素完成與appendleft()相同的處理
pop: 出隊,從隊列右端刪除一個元素,并返回該元素
popleft: 出隊,從隊列左端刪除一個元素,并返回該元素
rotate:將隊列的某些元素按某一方向進行旋轉(zhuǎn)
1 from collections importdeque2 queue = deque()
3 queue =deque(maxlen=n) # 限制queue的最大長度為n4 queue.append('one') #deque(['one'])
5 queue.appendleft('two') #deque(['two', 'one'])
6 queue.extend('three') #deque(['two', 'one', 't', 'h', 'r', 'e', 'e'])
7 queue.extendleft('four') #deque(['r', 'u', 'o', 'f', 'two', 'one', 't', 'h', 'r', 'e', 'e'])
8 queue.pop() #deque(['r', 'u', 'o', 'f', 'two', 'one', 't', 'h', 'r', 'e'])
9 queue.popleft() #deque(['u', 'o', 'f', 'two', 'one', 't', 'h', 'r', 'e'])
10 queue.rotate(2) #deque(['r', 'e', 'u', 'o', 'f', 'two', 'one', 't', 'h']) ,參數(shù)為正數(shù)n時,將右端的n個元素依次插入到左端
11 queue.rotate(-3) #deque(['o', 'f', 'two', 'one', 't', 'h', 'r', 'e', 'u']) ,參數(shù)為負數(shù)n時,將左端的n個元素依次插入到右端
參考博文: https://www.jb51.net/article/88139.htm
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431953239820157155d21c494e5786fce303f3018c86000
https://docs.python.org/3/library/collections.html#collections.deque
總結(jié)
以上是生活随笔為你收集整理的python 栈和队列_python 栈和队列的基本实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: apple ii 模拟器 mac_苹果自
- 下一篇: centos安装mysql5.7.12_