Python will list a list of maintenance into a stack

  • 1, simple to understand:

Stack (Stack), also known as the stack, which is a linear form of operation is limited.

Defining a linear table insertion and deletion operations only in the trailer. This input is called the stack, relatively, and the other end is called the bottom of the stack.

Inserting a new element to the stack, also referred to push, push or stack, which is a new element into the top element of the above, making the new top of the stack;

Also known as a stack to remove elements from the stack or unstack, it is to delete the top element, so that adjacent elements becomes the new top of the stack.

"Stack" who store goods or place for travelers to stay, can be extended to the warehouse, transit station, so into the computer field, that means a place temporarily stored data, so only the stack, the stack view.

- Baidu Encyclopedia

  • 2, code implementation:

The following is a simple implementation of the python list data type built into a stack maintained:

class Stack(object):
        """该类将list列表维护成一个栈"""

    def __init__(self):
        self.items = []

    def isEmpty(self):
        """判断栈是否为空"""
        return self.items == []

    def push(self, item):
        """添加一个新的元素item到栈顶"""
        self.items.append(item)

    def pop(self):
        """弹出栈顶元素"""
        return self.items.pop()

    def top(self):
        """返回栈顶元素"""
        return self.items[len(self.items) - 1]

    def size(self):
        """返回栈的元素个数"""
        return len(self.items)

Now, using the example of a stack Stack class after that be able to use the method:

stack = Stack()
print(stack.isEmpty())
print()
stack.push('you')
stack.push('love')
stack.push('I')
print(stack.top())
print(stack.size())
print(stack.isEmpty())
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack.size())

Print Results:

True
I
3
False
I
love
you
0

the above.

Guess you like

Origin www.cnblogs.com/sirxy/p/12148081.html