
上QQ阅读APP看书,第一时间看更新
5-3 Python中栈的应用
Python的列表(list)结构可以让我们很方便地实现前两节的栈操作,在这一节笔者将讲解使用Python内建列表直接模拟栈操作,以及使用列表功能重新诠释栈操作,同时我们也可以增加一些功能操作,下列将一一讲解。
5-3-1 使用列表(list)模拟栈操作
在Python程序语言中关于列表(list)有两个很重要的内建方法:
append( ):在列表末端加入数据,读者可以想成是栈的push方法。
pop( ):读取列表末端的数据同时删除该数据,读者可以想成是栈的pop方法。

程序实例ch5_1.py:使用Python的append( )模拟栈的push,使用Python的pop( )模拟栈的pop。

执行结果

5-3-2 自行建立stack类别执行相关操作
程序实例ch5_2.py:将Grape、Mango、Apple分别推入栈,然后输出有多少种水果在栈内。

执行结果

程序实例ch5_3.py:扩充设计ch5_2.py,将数据推入栈输出数量后,再将数据取出。在这个程序设计中,为了确认所有数据是否都已经取出,可以在Stack类别内增加isEmpty( )方法。

执行结果
