Python如何用列表構建棧結構

2021-10-06 13:49:14 字數 3134 閱讀 1452

1.1 問題

建立stack.py指令碼,要求如下:

棧是乙個後進先出的結構

編寫乙個程式,用列表實現棧結構

需要支援壓棧、出棧、查詢功能

1.2 方案

建立空列表儲存資料,建立4個函式,分別實現壓棧、出棧、查詢以及判斷函式呼叫的方法。

此程式需要注意的是堆疊的結構特點,先進後出,後進先出:

1.呼叫show_menu()函式後,利用while迴圈互動端輸出提示,請使用者input0/1/2/3任意數值,如果輸入的值不是0/1/2/3,列印輸入值無效請重新輸入並重新開始迴圈,如果輸入的值是3,停止整個迴圈,如果輸入的值是0/1/2通過字典鍵值對關聯關係,呼叫相對應函式

3.如上,如果輸入的值是1,呼叫出棧函式pop_it(),出棧函式如果stack列表中有資料,彈出列表最後乙個元素(根據堆疊結構特點stack.pop()中引數為空),如果stack列表沒有資料,輸出空列表

4.如果輸入的值是2,呼叫查詢函式view_it(),顯示當前列表

1.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:編寫指令碼

讓輸出的文字帶顏色:\033[31;1m高亮度紅色字型、\033[31;1m高亮度綠色字型、\033[0m關閉所有屬性

[root@localhost day04]# vim stack.py

#!/usr/bin/env python3

stack =

def push_it():

item = input('item to push: ')

def pop_it():

if stack:

print("\033[31;1mpopped %s\033[0m" % stack.pop())

else:

print('\033[31;1mempty stack\033[0m')

def view_it():

print("\033[32;1m%s\033[0m" % stack)

def show_menu():

prompt = """(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): """

cmds =

while true:

# strip() 方法用於移除字串頭尾指定的字元(預設為空格)

choice = input(prompt).strip()[0]

if choice not in '0123':

print('invalid input. try again.')

continue #結束本次迴圈

if choice == '3':

break #結束整個迴圈

cmds[choice]() # push_it() pop_it()

# if choice == '0':

# push_it()

# elif choice == '1':

# pop_it()

# elif choice == '2':

# view_it()

if __name__ == '__main__':

show_menu()

步驟二:測試指令碼執行

[root@localhost day04]# python3 stack.py

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 6

invalid input. try again.

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 0

item to push: nihao

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 1

popped nihao

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 2

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 0

item to push: a

(0) push_it

(1) pop_it

(2) view_it

please input your choice(0/1/2/3): 0

item to push: b

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 0

item to push: c

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 1

popped c

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 2

['a', 'b']

(0) push_it

(1) pop_it

(2) view_it

(3) quit

please input your choice(0/1/2/3): 3

(3) quit

Python 如何用列表實現棧和佇列

前面學習了列表的基礎知識,本著學以致用的原則,就想著如何通過列表來實現資料結構棧和佇列。x 建立乙個空列表,此處表示棧 x x a x a b x.pop 彈出棧頂元素 b b x a x.pop 彈出棧頂元素 a a x x.pop 試圖對乙個空棧做彈出操作,會報異常 traceback most...

如何用C 實現棧

簡單定義 棧就是一種只允許在表尾進行插入和刪除操作的線性表 舉乙個生活中的例子 我在乙個儲物箱中,堆了一堆衣服,我的一件球衣在最下面,而我要拿這件衣服,就意味著我必須將上面的衣服全部拿出來才可以,但是由於箱子只有乙個口,我也只能從上面拿東西,心裡還默默想著,當初就不該將球衣早早的放進去,導致結果就是...

如何用棧實現佇列功能以及如何用佇列實現棧功能

棧實現佇列的基本思路 構造兩個棧,其中乙個用來存放存進來的資料,另外乙個用來倒置其中的資料實現輸出。public static class twostacksqueue public void add int pushint public intpoll else if stackpop.empty...