使用一個佇列實現棧的 Python 程式
當需要使用單個佇列來實現棧時,需要一個“Stack_structure”類以及一個“Queue_structure”類。這些類中分別定義了相應的方法來新增和刪除棧和佇列中的值。
下面是相同的演示 -
示例
class Stack_structure:
def __init__(self):
self.q = Queue_structure()
def check_empty(self):
return self.q.check_empty()
def push_val(self, data):
self.q.enqueue_operation(data)
def pop_val(self):
for _ in range(self.q.size_calculate() - 1):
dequeued = self.q.dequeue_operation()
self.q.enqueue_operation(dequeued)
return self.q.dequeue_operation()
class Queue_structure:
def __init__(self):
self.items = []
self.size = 0
def check_empty(self):
return self.items == []
def enqueue_operation(self, data):
self.size += 1
self.items.append(data)
def dequeue_operation(self):
self.size -= 1
return self.items.pop(0)
def size_calculate(self):
return self.size
my_instance = Stack_structure()
print('Menu')
print('push <value>')
print('pop')
print('quit')
while True:
my_input = input('What operation would you like to perform ? ').split()
operation = my_input[0].strip().lower()
if operation == 'push':
my_instance.push_val(int(my_input[1]))
elif operation == 'pop':
if my_instance.check_empty():
print('The stack is empty.')
else:
print('The deleted value is : ', my_instance.pop_val())
elif operation == 'quit':
break輸出
Menu push <value> pop quit What operation would you like to perform ? push 89 What operation would you like to perform ? push 43 What operation would you like to perform ? push 76 What operation would you like to perform ? push 56 What operation would you like to perform ? pop The deleted value is : 56 What operation would you like to perform ? quit
解釋
建立一個“Stack_structure”類,該類初始化一個空列表。
定義一個“check_empty”方法來檢查棧是否為空。
定義另一個名為“push_val”的方法,該方法將元素新增到棧中。
定義另一個名為“pop_val”的方法,該方法從棧中刪除元素。
建立一個“Queue_structure”類,該類初始化一個空列表並將列表的大小賦值為 0。
定義一個“check_empty”方法來檢查佇列是否為空。
定義另一個名為“enqueue_operation”的方法,該方法將元素新增到佇列中。
定義另一個名為“dequeue_operation”的方法,該方法從佇列中刪除元素。
定義另一個名為“size_calculate”的方法,該方法確定佇列的大小。
定義此“Stack_structure”的一個例項。
給出四個選項 - 選單、入棧、出棧和退出。
根據使用者給出的輸入,對棧元素執行操作。
輸出顯示在控制檯上。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP