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()

 

 

posted @ 2022-01-13 21:43  M1stF0rest  阅读(58)  评论(1)    收藏  举报