Stack

This ordering principle is sometimes called LIFO, last-in first-out. It provides an ordering based on length of time in the collection. Newer items are near the top, while older items are near the base.

The Reversal Property of Stacks

The Stack Abstract Data Type
The stack abstract data type is defined by the following structure and operations. A stack is structured, as described above, as an ordered collection of items where items are added to and removed from the end called the “top.” Stacks are ordered LIFO. The stack operations are given below.

Stack() creates a new stack that is empty. It needs no parameters and returns an empty stack.

push(item) adds a new item to the top of the stack. It needs the item and returns nothing.

pop() removes the top item from the stack. It needs no parameters and returns the item. The stack is modified.

peek() returns the top item from the stack but does not remove it. It needs no parameters. The stack is not modified.

isEmpty() tests to see whether the stack is empty. It needs no parameters and returns a boolean value.

size() returns the number of items on the stack. It needs no parameters and returns an integer.

Implementing a Stack in Python

class Stack:#建立一个栈类
    #内部的方法是类的属性
     def __init__(self):#初始化,是一个LIST
         self.items = []

     def isEmpty(self):#是否为空
         return self.items == []

     def push(self, item):#LIST里加东西
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):#返回顶端的
         return self.items[len(self.items)-1]

     def size(self):#个数
         return len(self.items)


s=Stack()

print(s.isEmpty())
s.push(4)
print(s.peek())
s.push('dog')
print(s.peek())
s.push(True)
print(s.peek())
print(s.size())
# print(s.isEmpty())
s.push(8.4)
print(s.peek())
print(s.pop())
# print(s.pop())
print(s.size())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值