Python Data Structure 简明教程
Python - Stack
在英文词典中,堆栈一词意味着在一个物体上排列另一个物体。就像在这种数据结构中分配内存。它以类似的方式存储数据元素,就像一叠盘子在厨房中一个放在另一个上面。因此,堆栈数据结构允许在可以称为堆栈顶部的某一端进行操作。我们只能从堆栈的这个结尾添加元素或删除元素。
In the english dictionary the word stack means arranging objects on over another. It is the same way memory is allocated in this data structure. It stores the data elements in a similar fashion as a bunch of plates are stored one above another in the kitchen. So stack data strcuture allows operations at one end wich can be called top of the stack.We can add elements or remove elements only form this en dof the stack.
在堆栈中,最后插入序列中的元素将首先出来,因为我们只能从堆栈的顶部删除元素。这种特性称为后进先出 (LIFO) 特性。添加和删除元素的操作被称为 PUSH 和 POP 。以下程序中,我们实现为 add 和 remove 函数。我们声明一个空列表并使用 append() 和 pop() 方法添加和删除数据元素。
In a stack the element insreted last in sequence will come out first as we can remove only from the top of the stack. Such feature is known as Last in First Out(LIFO) feature. The operations of adding and removing the elements is known as PUSH and POP. In the following program we implement it as add and and remove functions. We declare an empty list and use the append() and pop() methods to add and remove the data elements.
PUSH into a Stack
让我们了解如何在堆栈中使用 PUSH。参考下面提到的程序−
Let us understand, how to use PUSH in Stack. Refer the program mentioned program below −
Example
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use peek to look at the top of the stack
def peek(self):
return self.stack[-1]
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
POP from a Stack
众所周知,我们只能从堆栈中删除最顶层的数据元素,我们实现一个这样做的 Python 程序。以下程序中的 remove 函数返回最顶层元素。我们通过首先计算堆栈的大小,然后使用内置的 pop() 方法找到最顶层元素来检查顶层元素。
As we know we can remove only the top most data element from the stack, we implement a python program which does that. The remove function in the following program returns the top most element. we check the top element by calculating the size of the stack first and then use the in-built pop() method to find out the top most element.
class Stack:
def __init__(self):
self.stack = []
def add(self, dataval):
# Use list append method to add element
if dataval not in self.stack:
self.stack.append(dataval)
return True
else:
return False
# Use list pop method to remove element
def remove(self):
if len(self.stack) <= 0:
return ("No element in the Stack")
else:
return self.stack.pop()
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())