使用兩個佇列實現棧的Python程式
當需要使用兩個佇列實現棧時,需要一個“Stack_structure”類和一個“Queue_structure”類。這兩個類中分別定義了用於向棧和佇列新增和刪除值的相應方法。
下面是演示:
示例
class Stack_structure:
def __init__(self):
self.queue_1 = Queue_structure()
self.queue_2 = Queue_structure()
def check_empty(self):
return self.queue_2.check_empty()
def push_val(self, data):
self.queue_1.enqueue_operation(data)
while not self.queue_2.check_empty():
x = self.queue_2.dequeue_operation()
self.queue_1.enqueue_operation(x)
self.queue_1, self.queue_2 = self.queue_2, self.queue_1
def pop_val(self):
return self.queue_2.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('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 56 What operation would you like to perform ? push 34 What operation would you like to perform ? push 78 What operation would you like to perform ? push 90 What operation would you like to perform ? pop The deleted value is: 90 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”的方法來確定佇列的大小。
定義了兩個“Queue_structure”的例項。
提供了四個選項:選單、入棧、出棧和退出。
根據使用者提供的輸入,對棧的元素執行操作。
輸出顯示在控制檯上。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP