Open In App

Implementation of stack using Doubly Linked List

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Stack and doubly linked lists are two important data structures with their own benefits. Stack is a data structure that follows the LIFO (Last In First Out) order and can be implemented using arrays or linked list data structures. Doubly linked list has the advantage that it can also traverse the previous node with the help of “previous” pointer.

Structure of Doubly Linked List

C++
// Declaration of Doubly Linked List
class Node {
public:
    int data;
    Node* next;
    Node* prev;
    Node(int val) {
        data = val;
        next = nullptr;
        prev = nullptr;
    }
};
Java
// Declaration of Doubly Linked List
class Node {
    public int data;
    public Node next;
    public Node prev;

    public Node(int val) {
        data = val;
        next = null;
        prev = null;
    }
}
Python
# Declaration of Doubly Linked List
class Node:
    def __init__(self, val):
        self.data = val
        self.next = None
        self.prev = None
C#
// Declaration of Doubly Linked List
class Node {
    public int data;
    public Node next;
    public Node prev;

    public Node(int val) {
        data = val;
        next = null;
        prev = null;
    }
}
JavaScript
// Declaration of Doubly Linked List
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
        this.prev = null;
    }
}

Stack Functions to be Implemented

Push()

  • If the stack is empty:
    • Create a new node and assign the given data to it.
    • Set both the “previous” and “next” pointers of the node to null as it is the first node in the doubly linked list (DLL).
    • Assign both “top” and “start” to this new node.
  • Otherwise:
    • Create a new node and assign the given data to it.
    • Set the “previous” pointer of the new node to the current “top” node.
    • Set the “next” pointer of the new node to null.
    • Update the “top” pointer to the new node, as it is now the top element of the stack.

Below is given the implementation:

C++
void push(int val) {
    Node* h = new Node(val);

    // If stack is empty
    // then make the new node as top
    if (isEmpty()) {
        h->prev = NULL;
        h->next = NULL;

        // As it is first node
        // so it is also top and start
        start = h;
        top = h;
    }
    else {
        top->next = h;
        h->next = NULL;
        h->prev = top;
        top = h;
    }
}
Java
void push(int d)
{
    Node n = new Node();
    n.data = d;
    if (n.isEmpty()) {
        n.prev = null;
        n.next = null;

        // As it is first node
        // if stack is empty
        start = n;
        top = n;
    }
    else {
        top.next = n;
        n.next = null;
        n.prev = top;
        top = n;
    }
}
Python
def push(self,element):
  newP = node(element)
  if self.start == None: 
    self.start = self.top = newP
    return
  newP.prev = self.top
  self.top.next = newP
  self.top = newP
C#
public void Push(int d)
{
    Node n = new Node();
    n.data = d;
    if (n.isEmpty())
    {
        n.prev = null;
        n.next = null;

        // As it is first node
        // if stack is empty
        start = n;
        top = n;
    }
    else
    {
        top.next = n;
        n.next = null;
        n.prev = top;
        top = n;
    }
}
JavaScript
function push(d) {
    var n = new Node();
    n.data = d;
    if (isEmpty()) {
    n.prev = null;
    n.next = null;
    start = n;
    top = n;
} 
else {
    top.next = n;
    n.next = null;
    n.prev = top;
    top = n;
}

Pop()

  • Check if the stack is empty.
    • If it is empty, print a message indicating that the stack is empty.
  • Otherwise:
    • Set top->prev->next to null.
    • Update top to top->prev.

Below is given the implementation:

C++
void pop()
{
    Node* n;
    n = top;
    if (isEmpty())
        printf("Stack is empty");
    else if (top == start) {
        top = NULL;
        start = NULL;
        free(n);
    }
    else {
        top->prev->next = NULL;
        top = n->prev;
        free(n);
    }
}
Java
void pop()
{
    Node n = top;
    if (n.isEmpty())
        System.out.println("Stack is empty");
    else if (top == start) {
        top = null;
        start = null;
    }
    else {
        top.prev.next = null;
        top = n.prev;
    }
}
Python
def pop(self):
  if self.isEmpty():
    print('List is Empty')
    return
  self.top =  self.top.prev
  if self.top != None: self.top.next = None
C#
public void pop()
{
    Node n ;
    n = top;
    if (n.isEmpty())
        Console.Write("Stack is empty");
    else if (top == start) {
        top = null;
        start = null;
        n = null;
    }
    else {
        top.prev.next = null;
        top = n.prev;
        n = null;
    }
}
JavaScript
function pop() {
    let n;
    n = top;
    if (isEmpty()) {
        console.log("Stack is empty");
    } 
    else if (top === start) {
        top = null;
        start = null;
        free(n);
    } 
    else {
        top.prev.next = null;
        top = n.prev;
        free(n);
    }
}

isEmpty()

  • Check the top pointer.
    • If top is null, return true.
    • Otherwise, return false.

Below is given the implementation:

C++
bool isEmpty()
{
    if (start == nullptr)
        return true;
    return false;
}
Java
boolean isEmpty()
{
    if (start ==  null)
        return true;
    return false;
}
Python
def isEmpty(self):
  if self.start: 
    return False
  return True
C#
public bool IsEmpty()
{
    if (start == null)
    {
        return true;
    }
    return false;
}
// This code is contributed by akashish__
JavaScript
function isEmpty() {
    return start == null;
}

printStack()

  • Check if the stack is empty.
    • If it is empty, print “Stack is empty.”
  • Otherwise, start from the start node and traverse the doubly linked list until the end.
    • Print the data of each node while traversing.

Below is given the implementation:

C++
void printStack()
{
    if (isEmpty())
        printf("Stack is empty");
    else {
        Node* ptr = start;
        while (ptr != NULL) {
            printf("%d   ", ptr->data);
            ptr = ptr->next;
        }
        printf("\n");
    }
}
Java
void printstack()
{
    if (isEmpty())
        System.out.println("Stack is empty");
    else {
        Node ptr = start;
        while (ptr != null) {
            System.out.print(ptr.data + " ");
            ptr = ptr.next;
        }
        System.out.println();
    }
}
Python
def printstack(self):
  if self.isEmpty():
    print('List is Empty')
    return
  curr = self.start
  while curr != None:
    print(curr.val,end = ' ')
    curr = curr.next
  print()
C#
void PrintStack()
{
    if (IsEmpty())
        Console.WriteLine("Stack is empty");
    else {
        Node ptr = start;
        while (ptr != null) {
            Console.Write(ptr.data + " ");
            ptr = ptr.next;
        }
        Console.WriteLine();
    }
}

// This code is contributed by akashish__
JavaScript
function printStack() {
    if (isEmpty()) {
        console.log("Stack is empty");
    } else {
        let ptr = start;
        while (ptr != null) {
            console.log(ptr.data + " ");
            ptr = ptr.next;
        }
        console.log("\n");
    }
}

stackSize()

  • Check if the stack is empty.
    • If it is empty, return 0.
  • Otherwise, initialize a counter and start from the start node.
    • Traverse the doubly linked list until the end, incrementing the counter for each node.
  • Return the final count.

Below is given the implementation:

C++
void stackSize()
{
    int c = 0;
    if (isEmpty())
        printf("Stack is empty");
    else {
        Node* ptr = start;
        while (ptr != NULL) {
            c++;
            ptr = ptr->next;
        }
    }
    printf("%d \n ", c);
}
Java
void stackSize()
{
    int c = 0;
    if (isEmpty())
        System.out.println("Stack is empty");
    else {
       Node ptr = start;
        while (ptr != null) {
            c++;
            ptr = ptr.next;
        }
    }
    System.out.println(c);
}
Python
def stackSize(self):
  curr = self.start
  len = 0
  while curr != None:
    len += 1
    curr = curr.next
  print(len)
C#
static void stackSize()
{
    int c = 0;
    if (IsEmpty())
        Console.WriteLine("Stack is empty");
    else
    {
        Node ptr = start;
        while (ptr != null)
        {
            c++;
            ptr = ptr.next;
        }
    }
    Console.WriteLine("{0}", c);
}
JavaScript
function stackSize() {
    let c = 0;
    if (isEmpty()) {
        console.log("Stack is empty");
    } else {
        let ptr = start;
        while (ptr !== null) {
            c++;
            ptr = ptr.next;
        }
    }
    console.log(c);
}

topElement()

  • Check if the stack is empty.
    • If it is empty, print that there is no top element.
  • Otherwise, print the data stored in the top node of the stack.

Below is given the implementation:

C++
void topElement()
{
    if (isEmpty())
        printf("Stack is empty");
    else
        printf(%d", top->data);
}
Java
void topelement()
{
    if (isEmpty())
        System.out.println("Stack is empty");
    else
        System.out.println(top.data);
}
Python
def topelement(self):  
  if self.isEmpty():
    print("Stack is empty") 
  else:
    print(self.top.val) 
C#
void TopElement()
{
    if (IsEmpty())
        Console.WriteLine("Stack is empty");
    else
        Console.WriteLine(top.data);
}
JavaScript
function topElement() {
    if (isEmpty()) {
        console.log("Stack is empty");
    } else {
        console.log(top.data);
    }
}

Implementation of Stack using Doubly Linked List

Implementation of Stack using Doubly Linked List:

Below is given the implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// DLL Node structure
class Node {
public:
    int data;
    Node* next;
    Node* prev;
    Node(int d) {
        data = d;
        next = nullptr;
        prev = nullptr;
    }
};

// Doubly Linked List structure
class DLL {
    Node* start;
    Node* top;
public:
    DLL() {
        start = nullptr;
        top = nullptr;
    }

    // Check if stack is empty
    bool isEmpty() {
        return start == nullptr;
    }

    // add element to stack
    void push(int val) {
        Node* cur = new Node(val);

        // if stack is empty, 
        // set start and top to cur
        if (isEmpty()) {
            start = cur;
            top = cur;
        }

        // else add cur to the top of stack
        else {
            top->next = cur;
            cur->prev = top;
            top = cur;
        }
    }

    // remove top element from stack
    void pop() {
        Node* cur = top;

        // if stack is empty, return
        if (isEmpty()) {
            cout << "Stack is Empty";
            return;
        }

        // else if there is only one element
        else if (top == start) {
            top = nullptr;
            start = nullptr;
            delete cur;
        }

        // else remove the top element
        else {
            top->prev->next = nullptr;
            top = cur->prev;
            delete cur;
        }
    }

    // print the top element
    void topElement() {
        if (isEmpty())
            cout << "Stack is empty";
        else
            cout << top->data << endl;
    }

    // find the stack size
    void stackSize() {
        int cnt = 0;
        Node* ptr = start;
        while (ptr != nullptr) {
            cnt++;
            ptr = ptr->next;
        }
        cout << cnt << endl;
    }

    // print the stack
    void printStack() {
        Node* ptr = start;
        while (ptr != nullptr) {
            cout << ptr->data << " ";
            ptr = ptr->next;
        }
        cout << endl;
    }
};

int main() {
    DLL stack;
    stack.push(2);
    stack.push(5);
    stack.push(10);
    stack.printStack();
    stack.topElement();
    stack.stackSize();
    stack.pop();
    stack.printStack();
    stack.topElement();
    stack.stackSize();
    return 0;
}
Java
import java.util.*;

class DLL {
    Node start;
    Node top;

    public DLL() {
        start = null;
        top = null;
    }

    // Check if stack is empty
    public boolean isEmpty() {
        return start == null;
    }

    // add element to stack
    public void push(int val) {
        Node cur = new Node(val);

        // if stack is empty, 
        // set start and top to cur
        if (isEmpty()) {
            start = cur;
            top = cur;
        }

        // else add cur to the top of stack
        else {
            top.next = cur;
            cur.prev = top;
            top = cur;
        }
    }

    // remove top element from stack
    public void pop() {
        Node cur = top;

        // if stack is empty, return
        if (isEmpty()) {
            System.out.print("Stack is Empty");
            return;
        }

        // else if there is only one element
        else if (top == start) {
            top = null;
            start = null;
            // In Java, garbage collector handles deletion
        }

        // else remove the top element
        else {
            top.prev.next = null;
            top = cur.prev;
            // In Java, garbage collector handles deletion
        }
    }

    // print the top element
    public void topElement() {
        if (isEmpty())
            System.out.print("Stack is empty");
        else
            System.out.println(top.data);
    }

    // find the stack size
    public void stackSize() {
        int cnt = 0;
        Node ptr = start;
        while (ptr != null) {
            cnt++;
            ptr = ptr.next;
        }
        System.out.println(cnt);
    }

    // print the stack
    public void printStack() {
        Node ptr = start;
        while (ptr != null) {
            System.out.print(ptr.data + " ");
            ptr = ptr.next;
        }
        System.out.println();
    }
}

class Node {
    int data;
    Node next;
    Node prev;

    Node(int d) {
        data = d;
        next = null;
        prev = null;
    }
}

class GfG {
    public static void main(String[] args) {
        DLL stack = new DLL();
        stack.push(2);
        stack.push(5);
        stack.push(10);
        stack.printStack();
        stack.topElement();
        stack.stackSize();
        stack.pop();
        stack.printStack();
        stack.topElement();
        stack.stackSize();
    }
}
Python
# DLL Node structure
class Node:
    def __init__(self, d):
        self.data = d
        self.next = None
        self.prev = None

# Doubly Linked List structure
class DLL:
    def __init__(self):
        self.start = None
        self.top = None

    # Check if stack is empty
    def isEmpty(self):
        return self.start is None

    # add element to stack
    def push(self, val):
        cur = Node(val)

        # if stack is empty, 
        # set start and top to cur
        if self.isEmpty():
            self.start = cur
            self.top = cur
        # else add cur to the top of stack
        else:
            self.top.next = cur
            cur.prev = self.top
            self.top = cur

    # remove top element from stack
    def pop(self):
        cur = self.top

        # if stack is empty, return
        if self.isEmpty():
            print("Stack is Empty", end="")
            return
        # else if there is only one element
        elif self.top == self.start:
            self.top = None
            self.start = None
            del cur
        # else remove the top element
        else:
            self.top.prev.next = None
            self.top = cur.prev
            del cur

    # print the top element
    def topElement(self):
        if self.isEmpty():
            print("Stack is empty", end="")
        else:
            print(self.top.data)

    # find the stack size
    def stackSize(self):
        cnt = 0
        ptr = self.start
        while ptr is not None:
            cnt += 1
            ptr = ptr.next
        print(cnt)

    # print the stack
    def printStack(self):
        ptr = self.start
        while ptr is not None:
            print(ptr.data, end=" ")
            ptr = ptr.next
        print()

if __name__ == "__main__":
    stack = DLL()
    stack.push(2)
    stack.push(5)
    stack.push(10)
    stack.printStack()
    stack.topElement()
    stack.stackSize()
    stack.pop()
    stack.printStack()
    stack.topElement()
    stack.stackSize()
C#
using System;
using System.Collections.Generic;

class Node {
    public int data;
    public Node next;
    public Node prev;

    public Node(int d) {
        data = d;
        next = null;
        prev = null;
    }
}

class DLL {
    static Node start;
    static Node top;

    public DLL() {
        start = null;
        top = null;
    }

    // Check if stack is empty
    public bool isEmpty() {
        return start == null;
    }

    // add element to stack
    public void push(int val) {
        Node cur = new Node(val);

        // if stack is empty, 
        // set start and top to cur
        if (isEmpty()) {
            start = cur;
            top = cur;
        }
        // else add cur to the top of stack
        else {
            top.next = cur;
            cur.prev = top;
            top = cur;
        }
    }

    // remove top element from stack
    public void pop() {
        Node cur = top;

        // if stack is empty, return
        if (isEmpty()) {
            Console.Write("Stack is Empty");
            return;
        }
        // else if there is only one element
        else if (top == start) {
            top = null;
            start = null;
            // Garbage collector handles deletion
        }
        // else remove the top element
        else {
            top.prev.next = null;
            top = cur.prev;
        }
    }

    // print the top element
    public void topElement() {
        if (isEmpty())
            Console.Write("Stack is empty");
        else
            Console.WriteLine(top.data);
    }

    // find the stack size
    public void stackSize() {
        int cnt = 0;
        Node ptr = start;
        while (ptr != null) {
            cnt++;
            ptr = ptr.next;
        }
        Console.WriteLine(cnt);
    }

    // print the stack
    public void printStack() {
        Node ptr = start;
        while (ptr != null) {
            Console.Write(ptr.data + " ");
            ptr = ptr.next;
        }
        Console.WriteLine();
    }
}

class GfG {
    public static void Main(string[] args) {
        DLL stack = new DLL();
        stack.push(2);
        stack.push(5);
        stack.push(10);
        stack.printStack();
        stack.topElement();
        stack.stackSize();
        stack.pop();
        stack.printStack();
        stack.topElement();
        stack.stackSize();
    }
}
JavaScript
// Declaration of DLL Node structure
class Node {
    constructor(d) {
        this.data = d;
        this.next = null;
        this.prev = null;
    }
}

// Doubly Linked List structure
class DLL {
    static start = null;
    static top = null;

    // Check if stack is empty
    static isEmpty() {
        return DLL.start === null;
    }

    // add element to stack
    static push(val) {
        let cur = new Node(val);

        // if stack is empty, 
        // set start and top to cur
        if (DLL.isEmpty()) {
            DLL.start = cur;
            DLL.top = cur;
        }
        // else add cur to the top of stack
        else {
            DLL.top.next = cur;
            cur.prev = DLL.top;
            DLL.top = cur;
        }
    }

    // remove top element from stack
    static pop() {
        let cur = DLL.top;

        // if stack is empty, return
        if (DLL.isEmpty()) {
            console.log("Stack is Empty");
            return;
        }
        // else if there is only one element
        else if (DLL.top === DLL.start) {
            DLL.top = null;
            DLL.start = null;
            // No explicit deletion needed in JavaScript
        }
        // else remove the top element
        else {
            DLL.top.prev.next = null;
            DLL.top = cur.prev;
            // No explicit deletion needed in JavaScript
        }
    }

    // print the top element
    static topElement() {
        if (DLL.isEmpty())
            console.log("Stack is empty");
        else
            console.log(DLL.top.data);
    }

    // find the stack size
    static stackSize() {
        let cnt = 0;
        let ptr = DLL.start;
        while (ptr !== null) {
            cnt++;
            ptr = ptr.next;
        }
        console.log(cnt);
    }

    // print the stack
    static printStack() {
        let ptr = DLL.start;
        let output = "";
        while (ptr !== null) {
            output += ptr.data + " ";
            ptr = ptr.next;
        }
        console.log(output);
    }
}

function main() {
    DLL.push(2);
    DLL.push(5);
    DLL.push(10);
    DLL.printStack();
    DLL.topElement();
    DLL.stackSize();
    DLL.pop();
    DLL.printStack();
    DLL.topElement();
    DLL.stackSize();
}

main();

Output
2 5 10 
10
3
2 5 
5
2

Time complexity:

  • push(): O(1) as we are not traversing the entire list.
  • pop(): O(1) as we are not traversing the entire list.
  • isEmpty(): O(1) as we are checking only the head node.
  • topElement(): O(1) as we are printing the value of the head node only.
  • stackSize(): As we traversed the whole list, it will be O(n), where n is the number of nodes in the linked list.
  • printStack(): As we traversed the whole list, it will be O(n), where n is the number of nodes in the linked list.

Auxiliary Space: O(n), to store the elements in the doubly linked list.



Next Article
Practice Tags :

Similar Reads