Open In App

Python | Stack using Doubly Linked List

Last Updated : 05 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A stack is a collection of objects that are inserted and removed using Last in First out Principle(LIFO). User can insert elements into the stack, and can only access or remove the recently inserted object on top of the stack. The main advantage of using LinkedList over array for implementing stack is the dynamic allocation of data whereas in the array, the size of the stack is restricted and there is a chance of stack overflow error when the size of the stack is exceeded the maximum size.

Stack Operations:

1. push() : Insert the element into Stack and assign the top pointer to the element.
2. pop() : Return top element from the Stack and move the top pointer to the second element of the Stack.
3. top() : Return the top element.
4. size() : Return the Size of the Stack.
5. isEmpty() : Return True if Stack is Empty else return False.
6. printstack() : Print all elements of the stack.

Below is the implementation of the above-mentioned stack operations using Doubly LinkedList in Python:

Implementation of Stack using Doubly Linked List 


Python3




# A complete working Python program to demonstrate all
# stack operations using a doubly linked list
 
# Node class
class Node:
 
# Function to initialise the node object
    def __init__(self, data):
        self.data = data # Assign data
        self.next = None # Initialize next as null
        self.prev = None # Initialize prev as null       
         
# Stack class contains a Node object
class Stack:
    # Function to initialize head
    def __init__(self):
        self.head = None
         
# Function to add an element data in the stack
    def push(self, data):
 
        if self.head is None:
            self.head = Node(data)
        else:
            new_node = Node(data)
            self.head.prev = new_node
            new_node.next = self.head
            new_node.prev = None
            self.head = new_node
             
             
# Function to pop top element and return the element from the stack
    def pop(self):
 
        if self.head is None:
            return None
        elif self.head.next is None:
            temp = self.head.data
            self.head = None
            return temp
        else:
            temp = self.head.data
            self.head = self.head.next
            self.head.prev = None
            return temp
 
 
 
 
# Function to return top element in the stack
    def top(self):
 
        return self.head.data
 
 
# Function to return the size of the stack
    def size(self):
 
        temp = self.head
        count = 0
        while temp is not None:
            count = count + 1
            temp = temp.next
        return count
     
     
# Function to check if the stack is empty or not 
    def isEmpty(self):
 
        if self.head is None:
           return True
        else:
           return False
             
 
# Function to print the stack
    def printstack(self):
         
        print("stack elements are:")
        temp = self.head
        while temp is not None:
            print(temp.data, end ="->")
            temp = temp.next          
         
 
# Code execution starts here        
if __name__=='__main__':
 
# Start with the empty stack
  stack = Stack()
 
# Insert 4 at the beginning. So stack becomes 4->None
  print("Stack operations using Doubly LinkedList")
  stack.push(4)
 
# Insert 5 at the beginning. So stack becomes 4->5->None
  stack.push(5)
 
# Insert 6 at the beginning. So stack becomes 4->5->6->None
  stack.push(6)
 
# Insert 7 at the beginning. So stack becomes 4->5->6->7->None
  stack.push(7)
 
# Print the stack
  stack.printstack()
 
# Print the top element
  print("\nTop element is ", stack.top())
 
# Print the stack size
  print("Size of the stack is ", stack.size())
 
# pop the top element
  stack.pop()
 
# pop the top element
  stack.pop()
   
# two elements are popped
# Print the stack
  stack.printstack()
   
# Print True if the stack is empty else False
  print("\nstack is empty:", stack.isEmpty())
 
#This code is added by Suparna Raut


Output:

Stack operations using Doubly LinkedList
stack elements are:
7->6->5->4->
Top element is  7
Size of the stack is  4
stack elements are:
5->4->
stack is empty: False

Time Complexity for operations:

  • Push(): O(1)
  • pop(): O(1)
  • top(): O(1)
  • size(): O(N)
  • isEmpty(): O(1)
  • printStack(): O(N)

Auxiliary Space for operations:

  • Push(): O(1)
  • pop(): O(1)
  • top(): O(1)
  • size(): O(1)
  • isEmpty(): O(1)
  • printStack(): O(1)


Previous Article
Next Article

Similar Reads

Implementation of stack using Doubly Linked List
Stack and doubly linked lists are two important data structures with their own benefits. Stack is a data structure that follows the LIFO technique 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. Doubly Linked Lis
15+ min read
Difference between Singly linked list and Doubly linked list
Introduction to Singly linked list : A singly linked list is a set of nodes where each node has two fields 'data' and 'link'. The 'data' field stores actual piece of information and 'link' field is used to point to next node. Basically the 'link' field stores the address of the next node. Introduction to Doubly linked list : A Doubly Linked List (D
2 min read
When is Doubly Linked List more Efficient than Singly Linked List?
Did you know there are some cases where a Doubly Linked List is more efficient than a Singly Linked List, even though it takes more memory compared to a Singly Linked List? What are those Cases? Well, we will discuss that in the following article, But first, let's talk about Singly and linked lists: What is a Singly Linked List?A singly linked list
4 min read
Is two way linked list and doubly linked list same?
Yes, a two-way linked list and a doubly linked list are the same. Both terms refer to a type of linked list where each node contains a reference to the next node as well as the previous node in the sequence. The term “two-way” emphasizes the ability to move in both directions through the list, while “doubly” highlights that there are two links per
3 min read
XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
In the previous post, we discussed how a Doubly Linked can be created using only one space for the address field with every node. In this post, we will discuss the implementation of a memory-efficient doubly linked list. We will mainly discuss the following two simple functions. A function to insert a new node at the beginning.A function to travers
10 min read
XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
In this post, we're going to talk about how XOR linked lists are used to reduce the memory requirements of doubly-linked lists. We know that each node in a doubly-linked list has two pointer fields which contain the addresses of the previous and next node. On the other hand, each node of the XOR linked list requires only a single pointer field, whi
15+ min read
Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ min read
Python | Queue using Doubly Linked List
A Queue is a collection of objects that are inserted and removed using First in First out Principle(FIFO). Insertion is done at the back(Rear) of the Queue and elements are accessed and deleted from first(Front) location in the queue. Queue Operations:1. enqueue() : Adds element to the back of Queue. 2. dequeue() : Removes and returns the first ele
3 min read
Convert Binary Tree to Circular Doubly Linked List using Linear extra space
Given a Binary Tree, convert it to a Circular Doubly Linked List. The left and right pointers in nodes are to be used as previous and next pointers, respectively, in the converted Circular Linked List.The order of nodes in the List must be the same as in the order of the given Binary Tree.The first node of Inorder traversal must be the head node of
12 min read
Reverse a Doubly linked list using recursion
Given a doubly linked list. Reverse it using recursion. Original Doubly linked list Reversed Doubly linked list We have discussed Iterative solution to reverse a Doubly Linked List Algorithm: If list is empty, return Reverse head by swapping head->prev and head->next If prev = NULL it means that list is fully reversed. Else reverse(head->p
9 min read
three90RightbarBannerImg