Implementation of Stack using Linked List

Stack: It is a linear data structure that follows the LIFO principle Imagine it as stacking plates on top of each other the plate you will put last will be the first plate you take out Stack also works similarly.

Applications of Stack:

  • It is used for computing mathematical operations.

  • Web browsers use stack to keep track of the webpages you visit they oush the webpage you visit in the stack.

  • Backtracking Algorithms

Although we can do all the stack operation of stack in c++ using STL library but to gain a deeper understanding of the stack we will make out own and perform some of the operations that too using Linked List.

#include <iostream>
using namespace std;
struct Node{ // initializing node
    int data;
    Node *next;
};
Node *head = NULL;
void push(int val){ // push operation in stack 
    Node* ptr = new Node; // making ptr of Node datatype
    ptr->data=val; //initializinf data of ptr to value 
    ptr->next=head; // initializing next pointer of ptr to head
    head = ptr; 
}
// what happens is when we push an element in the stack head pointer points to
// that particular node so in that way head pointer will always point towards the 
// new element
void pop(){
    Node *ptr = head; // giving head to ptr
    head = head->next; // updating head to next
    delete(ptr); // popping the ptr
}
// in pop function what we did was we initialized ptr to head and then deleted the head
// what this does is it pops the recently added value in stack thus following rules
// LIFO
void display_stack(){
    Node *temp = head;
    while(temp!=NULL){
        cout<<temp->data<<"->";
        temp = temp->next;
    }
}
int main()
{
    push(89);
    push(88);
    push(87);
    display_stack();

    return 0;
}