Implementation of stack using Doubly Linked List
Last Updated :
23 Apr, 2025
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();
Output2 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.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read