Day 5 Stack
A stack is a data structure which contains an ordered set of data.
Stacks provide three methods for interaction:
- Push - adds data to the “top” of the stack
- Pop - returns and removes data from the “top” of the stack
- Peek - returns data from the “top” of the stack without removing it
Stacks can be implemented using a linked list as the underlying data structure because it’s more efficient than a list or array.
A constraint that may be placed on a stack is its size. This is done to limit and quantify the resources the data structure will take up when it is “full.”
Attempting to push data onto an already full stack will result in a stack overflow. Similarly, if you attempt to pop data from an empty stack, it will result in a stack underflow.
In a word, a stack processes data following the pattern of Last In, First Out (LIFO) (Where a queue applies the pattern of First In, First Out)
Below is the implementation of a stack in python. In the end I use an instance of pizza stack.
Notice that I import the code from Node. Complete code is here:https://www.cnblogs.com/M1stF0rest/p/15758387.html
from node import Node class Stack: def __init__(self, limit=1000): self.top_item = None self.size = 0 self.limit = limit def push(self, value): if self.has_space(): item = Node(value) item.set_next_node(self.top_item) self.top_item = item self.size += 1 print("Adding {} to the pizza stack!".format(value)) else: print("No room for {}!".format(value)) def pop(self): if not self.is_empty(): item_to_remove = self.top_item self.top_item = item_to_remove.get_next_node() self.size -= 1 print("Delivering " + item_to_remove.get_value()) return item_to_remove.get_value() print("All out of pizza.") def peek(self): if not self.is_empty(): return self.top_item.get_value() print("Nothing to see here!") def has_space(self): return self.limit > self.size def is_empty(self): return self.size == 0 # Defining an empty pizza stack pizza_stack = Stack(6) # Adding pizzas as they are ready until we have pizza_stack.push("pizza #1") pizza_stack.push("pizza #2") pizza_stack.push("pizza #3") pizza_stack.push("pizza #4") pizza_stack.push("pizza #5") pizza_stack.push("pizza #6") # Uncomment the push() statement below: pizza_stack.push("pizza #7") # Delivering pizzas from the top of the stack down print("The first pizza to deliver is " + pizza_stack.peek()) pizza_stack.pop() pizza_stack.pop() pizza_stack.pop() pizza_stack.pop() pizza_stack.pop() pizza_stack.pop() # Uncomment the pop() statement below: pizza_stack.pop()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通