Does python have a stack?

藏色散人
Release: 2019-08-01 16:08:34
Original
4953 people have browsed it

Does python have a stack?

Does python have a stack?

Python does have a stack. Stacks are a linear data structure that can only store and retrieve data by accessing one end of it. It has the characteristics of last in first out (LIFO).

The two main operations on the stack are pushing an element onto the stack and popping an element off the stack.

Push into the stack using the push() method, pop out the stack using the pop() method

Another common operation is to preview the element on the top of the stack . Although the pop() method can access the element on the top of the stack, after calling this method, the element on the top of the stack is also permanently deleted from the stack. The peek() method only returns the top element of the stack without deleting it

In order to record the position of the top element of the stack, and also to mark where new elements can be added, we use the variable top. When pushed into the stack When an element is removed from the stack, the variable increases; when an element is popped from the stack, the variable decreases.

push(), pop() and peek() are the three main methods of the stack, but there are other methods of the stack. Common operations with attributes

stack:

  Stack()   建立一个空的栈对象
  push()    把一个元素添加到栈的最顶层
  pop()     删除栈最顶层的元素,并返回这个元素
  peek()    返回最顶层的元素,并不删除它
  isEmpty() 判断栈是否为空
  size()    返回栈中元素的个数
Copy after login
#-*- coding:?UTF-8 -*-
__author__ = 'Administrator'
#python的list对象模拟栈的实现
class Stack:
    #模拟栈
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return len(self.items)==0
    def push(self,item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        if not self.isEmpty():
            return self.items[len(self.items)-1]
    def size(self):
        return len(self.items)
#创建一个栈对象,并加入操作方法
s = Stack()
print(s.isEmpty())
s.push(4)
s.push('DOG')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())
Copy after login

Related recommendations: "Python Tutorial"

The above is the detailed content of Does python have a stack?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!