Instagram
youtube
Facebook
Twitter

Stacks

Stacks Introduction

  • A stack is a data structure that acts as a collection of elements and performs the two basic operations push (insertion) and pop (deletion). In this post, we'll examine various Python implementation and usage strategies for the stack..
  • The top element is always removed first from a stack and is always added to it whenever a new element is added. 
  • Stacks contain an ordered set of data.
  • Stack also provides a method named peek which returns the data at the top of the stack.
  • This is a Last In, First Out or LIFO structure. A less frequently used term is First In, Last Out, or FILO.
  • Stacks are used to implement searches in Graphs and Trees, which are other complex data structures.
  • Examples include: Back and Forward in a browser, A pile of books, utensils in a dishwasher, In recursion, etc.

Push Pop

Stacks Implementation

These are the following Methods used in Stacks Implementation:

 

  • stack.isEmpty()

    • The stack.isEmpty() method returns True if the stack is empty. Else, returns False

 

  • stack.length()
    • The stack.length() method returns the length of the stack.

 

  • stack.top()
    • The stack.top() method returns the top element in the stack.

 

  • stack.push(x)
    • The stack.push() method inserts the element, x to the top of the stack.

 

  • stack.pop()
    • The stack.pop() method removes the top element of the stack and returns it.

A list can be used to create stacks. And We can use append and pop method of lists.

class Stack:

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

    def isEmpty(self) -> bool:
        return True if len(self.stack) == 0 else False

    def length(self) -> int:
        return len(self.stack)

    def top(self) -> int:
        return self.stack[-1]  

    def push(self, m: int) -> None:
        self.m = m
        self.stack.append(m)       

    def pop(self) -> None:
        self.stack.pop()