C++ program to implement Stack using Linked List

There are two ways to implement Stack in C C++

  1. Using Array
  2. Using Linked List

Here I’ve Discussed how to implement Stack using Linked List.

For Stack implementation using Arrays see this:

Program to implement Stack using Array

PROGRAM:

#include <iostream>
#include <stdio.h>
#include <conio.h>
using namespace std;
struct node
{
    int data;
    node *next;
}*front = NULL, *rear = NULL, *p = NULL, *np = NULL;
void push(int x)
{
    np = new node;
    np->data = x;
    np->next = NULL;
    if(front == NULL)
    {
        front = rear = np;
        rear->next = NULL;
    }
    else
    {
        rear->next = np;
        rear = np;
        rear->next = NULL;
    }
}
int remove()
{
    int x;
    if (front == NULL)
    {
        cout<<"empty queue\n";
    }
    else
    {
        p = front;
        x = p->data;
        front = front->next;
        delete(p);
        return(x);
    }
}
int main()
{
    int n, c = 0, x;
    cout<<"Enter the number of values to be pushed into queue\n";
    cin>>n;
    while (c < n)
    {
	cout<<"Enter the value to be entered into queue\n";
	cin>>x;
        push(x);
        c++;
    }
    cout<<"\n\nRemoved Values\n\n";
    while(true)
    {
        if (front != NULL)
            cout<<remove()<<endl;
	else
	    break;
    }
    getch();
}

OUTPUT:

implement stack using linked list

(Visited 126 times, 1 visits today)
Program to convert Fahrenheit to Celsius in C++
Program to implement Queue using Linked List C++

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>