Implement a Stack using Linked Lists

Here comes the fun part or i should say the extensive part. We can learn one data structure and then mess with it to create other data structures, here we are going to see how to implement a Stack using a singly linked list. 

For this we must keep in mind that a stack follows Last in First out structure (LIFO), Now we are ready to tackle this problem with certain Stack operations like Push, pop, peek-to give top element and display in mind.

Code-->

Class Node{
    int data;
    Node* link;
};

Node* top;

//function to add element 
void push(int data)
{
        Node* temp= new Node(data);
        if(!temp)
        {
                cout<<"Overflow";
                exit(1);
        }    

    temp->link=top;
    top=temp;
}

int empty()
{
    return top==NULL;
}

int peek()
{
    if(!empty())
        return top->data;
    else
        exit(1);
}
//function to remove an element

void pop()
{
        Node* temp;
        if(top==NULL)
                cout<<"Underflow";
                exit(1);
        else
            temp=top;
            top=top->link;
            temp->link=NULL;
            free(temp);
}

//function to display elements
void display()
{
        Node* temp;
        if(top==NULL)
            cout<<"underflow";
            exit(1);
        else
            temp=top;
            while(temp!=NULL)
                cout<<temp->data;    
                temp=temp->link;
}




Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)