1. 什么是栈
- 栈(有时称为“后进先出栈”)是一个项的有序集合,其中添加移除新项总发生在同一端。这一端 通常称为“顶部”。与顶部对应的端称为“底部”。
- 栈的底部很重要,因为在栈中靠近底部的项是存储时间最长的。最近添加的项是最先会被移除的。这种排序原则有时被称为 LIFO,后进先出。它基于在集合内的时间长度做排序。较新的项靠近顶部,较旧的项靠近底部。
- python中对象在栈中的进出顺序,如Figure3所示
- 个人理解:我认为栈最大的特点在于反转栈中对象的顺序和优先级。
- 例子:每个 web 浏览器都有一个返回按钮。当你浏览网页时,这些网页被放置在一个栈中(实际是网页的网址)。你现在查看的网页在顶部,你第一个查看的网页在底部。如果按‘返回’按钮,将按相反的顺序浏览刚才的页面。
2.栈的抽象数据类型
- Stack() 创建一个空的新栈。 它不需要参数,并返回一个空栈。
- push(item)将一个新项添加到栈的顶部。它需要 item 做参数并不返回任何内容。
- pop() 从栈中删除顶部项。它不需要参数并返回 item 。栈被修改。
- peek() 从栈返回顶部项,但不会删除它。不需要参数。 不修改栈。
- isEmpty() 测试栈是否为空。不需要参数,并返回布尔值。
- size() 返回栈中的 item 数量。不需要参数,并返回一个整数。
- clear() 清空一个栈里的数据。不需要参数,
- iter() 迭代一个栈中的元素,从栈底到栈顶的顺序
3.python用列表实现栈结构
- 用列表模拟栈:
栈并不是python的内建类型,可以通过使用list来模拟栈,将列表的末尾看做栈的顶。
用这种方法的主要缺点是:所有其他的列表操作也可以操作这个栈,包括任意位置插入、替换和删除元素,这些操作就违反了栈作为一种抽象数据类型的本意。class Stack: """ a list_based stack implementation. """ #constructor def __init__(self): """ Sets the initial state of self, and the initial state is [] """ self.items = [] #accessor methods def iter(self): """ Supports iteration over a view of self. Visits items from bottom to top stack. :return: """ for i in range(len(self.items)): yield self.items[i] def isEmpty(self): """ Returns True if len(self) == 0, or False others. :return: """ return len(self.items) == 0 def peek(self): """ Returns the item at the top of the stack. Precondition: the stack is not empty. Raises: KeyError if the stack is empty. :return: """ if self.isEmpty(): return "The stack is empty" return self.items[len(self.items)-1] def size(self): """ return the len(self) :return: """ return len(self.items) def clear(self): """ Make self become empty. :return: """ self.items = [] def push(self,item): """ Adds item to the top of the stack. :param item:obj :return: None """ self.items.append(item) def pop(self): """ Removes and returns the item at the top of the stack. Precondition: the stack is not empty. Raises: KeyError if the stack is empty. Postcondition: the top item is removed from the stack. :return: """ if self.isEmpty(): return "The stack is empty" return self.items.pop()