DS – Stack using Single Linked List

Stack:

  • Stack follows LIFO (Last In First Out) rule.
  • We insert and remove elements from TOP only.

Stack model representation:

Stack operations:

  1. Push element: inserting element from the top of stack
  2. Pop element: Remove the top element if the stack is not empty
  3. Traverse: Display elements of stack if the stack is not empty

Node structure:

struct Node
{
            int data;
            struct Node *link;
};
struct Node *top = NULL;

Push():

  • Initially top is pointing to NULL value as no nodes in the list.
  • If we push new node, then the new node become top node.

Pop() :

  • To remove an element, first we need to check the Stack is empty or not.
  • If Stack is empty(top=NULL) à give a message.
  • If not empty, then remove the element and display value.
  • Then top should point to previous node.

Display():

  • If the Stack is Empty -> Give the message
  • If elements are present, we need to display from top to last node.

Scroll to Top