How to implement Stack using Link List?

Hello Programmer,

Are you afraid for link list ? In this tutorial I’ll show how to implement Stack using link list. A linked list is a linear collection of data elements whose order is not given by their physical placement in memory.

I assume you know Stack’s algorithm.(Which I have told in my previous content [stack])

Well,Implement the Stack in link list, first you’ve to define a structure which has two part, one is data part another one is address part.(address of next node).

typedef struct Node{
    int data;
    struct Node *next;
}node;

Then you have to initialize a pointer variable which data type is according to your node.

node *top;

Then initialize a function where define *top = 0

void initial(){
    top = 0;
}

Well, Our initial setup has done, Now implement the push function.

void push(int val){
    node *newNode;
    newNode = new node;
    newNode->data = val;
    newNode->next = top;
    top = newNode;
}

Let me explain how push function works. Here you can see the first line of push function I declare a pointer which data type is according to structure. Well, then using new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable. Check Our structure where I have defined two part (data and address part) ,so in this data part I store data which is I sent using push function’s parameter. Then address part I stored address of top (which I define initially).Then top equal to newNode which I created in push function.

Now display the values :

void display(node *top){
    node *temp = top;
    if(top == 0){
        cout<<"\nEmpty Stack!\n";
        return;
    }
    while(temp != 0){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}

Now time to implement pop function :

int pop(){
     if(top == 0){
        cout<<"\nEmpty Stack!\n";
        return -1;
    }
    node *temp;
    temp = top;
    int data = temp->data;
    top = top->next;
    free(temp);
    return data;
}

In this pop function first I have checked that our list has any node or not. If top equal to null or zero then we can write that our stack is empty. Then declare a node pointer which store our top node so that we can remove existing data from our memory. then return data.

Source code : https://github.com/AR-Shahin/Data_Structure_and_Algorithm/blob/main/Stack/stack_link_list_cpp.txt

1 thought on “How to implement Stack using Link List?”

Leave a Comment

Your email address will not be published. Required fields are marked *