What is a Stack?

Stack is a linear data structure in which the element inserted last is the element to be deleted first.
It is also called Last In First Out (LIFO).
In a stack, the last inserted element is at the top.

Operations

Operations of the stack are

  • push(): inserts an element into the stack at the end
  • pop(): deletes and returns the last inserted element from the stack
  • peek(): returns the last inserted element

Illustration

After inserting three elements in the stack, it will look like this:

%0 node_1 1 top_node top node_1->top_node
push(1)
%0 node_1 1 node_2 2 top_node top node_2->top_node
push(2)
%3 node_1 1 node_2 2 node_3 3 top_node top node_3->top_node
push(3)

After performing the pop operation twice, the stack elements will look like:

%0 node_1 1 node_2 2 top_node top node_2->top_node
pop()
%0 node_1 1 top_node top node_1->top_node
pop()

Implementation of stack operations

def push(stack,element):
    """insertion of 'element' into the stack"""
    stack.append(element)

def pop(stack):
   """deletes and returns the last inserted element"""
   if len(stack)==0:
       print("stack underflow")
       quit()
   return stack.pop()

def peek(stack):
   """returns the last inserted element"""
   if len(stack)==0:
       print("stack is empty")
       return -1
   return stack[-1]

Applications of the stack

Free Resources