Home Data Structure And AlgorithmsStack C++ Program to Implement Stack Using Linked List

C++ Program to Implement Stack Using Linked List

by Ankit Chauhan
3 minutes read

In this article, we’ll make a C++ program to implement stack using linked list and discover about different operation like push, pop and peek.

A stack is a data structure that follows the last-in, first-out (LIFO) principle. This means that the last element added to the stack is the first element to be removed. The basic operations of a stack are:

  • Push: Adds an element to the top of the stack.
  • Pop: Removes the element at the top of the stack and returns it.
  • Peek: Returns the element at the top of the stack without removing it.

Program to Implement Stack using Linked List

#include <iostream>

using namespace std;

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

Node *top = NULL;

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

int pop() {
  if (top == NULL) {
    cout << "Stack is empty" << endl;
    return -1;
  }

  int value = top->data;
  top = top->next;
  delete top;
  return value;
}

int peek() {
  if (top == NULL) {
    cout << "Stack is empty" << endl;
    return -1;
  }

  return top->data;
}

bool isEmpty() {
  return top == NULL;
}

void printStack() {
  Node *temp = top;
  while (temp != NULL) {
    cout << temp->data << " ";
    temp = temp->next;
  }
  cout << endl;
}

int main() {
  push(1);
  push(2);
  push(3);

  cout << "Stack: ";
  printStack();

  cout << "Popped element: " << pop() << endl;

  cout << "Stack: ";
  printStack();

  cout << "Peek: " << peek() << endl;

  cout << "Is stack empty? " << isEmpty() << endl;

  return 0;
}

Output

Stack: 1 2 3
Popped element: 3
Stack: 1 2
Peek: 2
Is stack empty? 0

This program first defines a struct Node to store the data and next pointer of a node in the linked list. Then, it defines global variables top to store the pointer to the top of the stack and isEmpty() to check if the stack is empty.

The functions push(), pop(), peek(), and printStack() are used to implement the stack operations. The push() function inserts a new node into the stack at the top. The pop() function removes the topmost node from the stack. The peek() function returns the data of the topmost node in the stack. The printStack() function prints all the nodes in the stack.

The main function of the program first pushes three elements into the stack. Then, it prints the stack. Next, it pops the topmost element from the stack and prints the stack again. Finally, it peeks the topmost element of the stack and checks if the stack is empty.

related posts

Leave a Comment

Enable Notifications OK No thanks