Open In App

Memory efficient doubly linked list

Last Updated : 18 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Asked by Varun Bhatia. 

Question: Write a code for implementation of doubly linked list with use of single pointer in each node. 

Solution: 

C++




#include <iostream>
using namespace std;
 
class Node {
public:
    int data;
    Node* next;
};
 
class CircularLinkedList {
private:
    Node* head;
public:
    CircularLinkedList() {
        head = nullptr;
    }
 
    void insert(int data) {
        Node* newNode = new Node();
        newNode->data = data;
        newNode->next = nullptr;
 
        if (head == nullptr) {
            head = newNode;
            head->next = head;
        } else {
            Node* temp = head;
            while (temp->next != head) {
                temp = temp->next;
            }
            temp->next = newNode;
            newNode->next = head;
        }
    }
 
    void print() {
        if (head == nullptr) {
            cout << "List is empty" << endl;
        } else {
            Node* temp = head;
            do {
                cout << temp->data << " ";
                temp = temp->next;
            } while (temp != head);
            cout << endl;
        }
    }
};
 
int main() {
    CircularLinkedList cll;
    cll.insert(1);
    cll.insert(2);
    cll.insert(3);
    cll.print(); 
    return 0;
}


Java




class Node {
    public int data;
    public Node next;
}
 
class CircularLinkedList {
    private Node head;
 
    public CircularLinkedList() {
        head = null;
    }
 
    public void insert(int data) {
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = null;
 
        if (head == null) {
            head = newNode;
            head.next = head;
        } else {
            Node temp = head;
            while (temp.next != head) {
                temp = temp.next;
            }
            temp.next = newNode;
            newNode.next = head;
        }
    }
 
    public void print() {
        if (head == null) {
            System.out.println("List is empty");
        } else {
            Node temp = head;
            do {
                System.out.print(temp.data + " ");
                temp = temp.next;
            } while (temp != head);
            System.out.println();
        }
    }
}
 
public class Main {
    public static void main(String[] args) {
        CircularLinkedList cll = new CircularLinkedList();
        cll.insert(1);
        cll.insert(2);
        cll.insert(3);
        cll.print();
    }
}


Python3




class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
class CircularLinkedList:
    def __init__(self):
        self.head = None
 
    def insert(self, data):
        new_node = Node(data)
 
        if self.head is None:
            self.head = new_node
            self.head.next = self.head
        else:
            temp = self.head
            while temp.next != self.head:
                temp = temp.next
            temp.next = new_node
            new_node.next = self.head
 
    def print(self):
        if self.head is None:
            print("List is empty")
        else:
            temp = self.head
            while True:
                print(temp.data, end=" ")
                temp = temp.next
                if temp == self.head:
                    break
            print()
 
# Create a CircularLinkedList object
cll = CircularLinkedList()
 
# Insert elements into the circular linked list
cll.insert(1)
cll.insert(2)
cll.insert(3)
 
# Print the circular linked list
cll.print()


C#




using System;
 
public class Node {
    public int data;
    public Node next;
}
 
public class CircularLinkedList {
    private Node head;
 
    public CircularLinkedList() {
        head = null;
    }
 
    public void Insert(int data) {
        Node newNode = new Node();
        newNode.data = data;
        newNode.next = null;
 
        if (head == null) {
            head = newNode;
            head.next = head;
        } else {
            Node temp = head;
            while (temp.next != head) {
                temp = temp.next;
            }
            temp.next = newNode;
            newNode.next = head;
        }
    }
 
    public void Print() {
        if (head == null) {
            Console.WriteLine("List is empty");
        } else {
            Node temp = head;
            do {
                Console.Write(temp.data + " ");
                temp = temp.next;
            } while (temp != head);
            Console.WriteLine();
        }
    }
}
 
public class Program {
    public static void Main() {
        CircularLinkedList cll = new CircularLinkedList();
        cll.Insert(1);
        cll.Insert(2);
        cll.Insert(3);
        cll.Print();
    }
}


Javascript




class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}
 
class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
 
  append(value) {
    const newNode = new Node(value);
 
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      this.tail = newNode;
    }
 
    this.length++;
  }
 
  prepend(value) {
    const newNode = new Node(value);
 
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      newNode.next = this.head;
      this.head = newNode;
    }
 
    this.length++;
  }
 
  insert(index, value) {
    if (index >= this.length) {
      this.append(value);
    } else if (index === 0) {
      this.prepend(value);
    } else {
      const newNode = new Node(value);
      let currentNode = this.head;
      let i = 0;
 
      while (i < index - 1) {
        currentNode = currentNode.next;
        i++;
      }
 
      newNode.next = currentNode.next;
      currentNode.next = newNode;
 
      this.length++;
    }
  }
 
  remove(index) {
    if (index === 0) {
      this.head = this.head.next;
    } else {
      let currentNode = this.head;
      let i = 0;
 
      while (i < index - 1) {
        currentNode = currentNode.next;
        i++;
      }
 
      currentNode.next = currentNode.next.next;
 
      if (index === this.length - 1) {
        this.tail = currentNode;
      }
    }
 
    this.length--;
  }
 
  toArray() {
    const result = [];
    let currentNode = this.head;
 
    while (currentNode) {
      result.push(currentNode.value);
      currentNode = currentNode.next;
    }
 
    return result;
  }
}


Output: 1 2 3

The given code implements a circular linked list data structure  using classes.

In this implementation, a circular linked list is created by maintaining a head pointer that points to the first node of the list. Each node of the list contains a data field and a next pointer that points to the next node in the list. The last node in the list has a next pointer that points back to the head node, thus forming a cycle.

The CircularLinkedList class has two member functions – insert and print.

The insert function takes an integer value as input and creates a new node with the given value. If the list is empty, the new node is assigned as the head node and its next pointer is set to point to itself. Otherwise, the function traverses the list to find the last node and appends the new node to the end of the list. Finally, the next pointer of the new node is set to point back to the head node, thus completing the cycle.

The print function traverses the circular linked list starting from the head node and prints the data field of each node until it reaches the head node again.

Time complexity:The time complexity of inserting a new node into the circular linked list is O(n) in the worst case, where n is the number of nodes in the list. This is because the function may need to traverse the entire list to find the last node. The time complexity of printing the circular linked list is also O(n) because every node is visited exactly once.

Space complexity:The space complexity of the circular linked list is O(n) because it requires a new node to be allocated in memory for each element inserted into the list.

This question is solved and very well explained at http://www.linuxjournal.com/article/6828. We also recommend to read http://en.wikipedia.org/wiki/XOR_linked_list



Previous Article
Next Article

Similar Reads

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
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
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
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
Why Linked List is implemented on Heap memory rather than Stack memory?
Pre-requisite: Linked List Data StructureStack vsHeap Memory Allocation The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind
14 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
Sort the given Matrix | Memory Efficient Approach
Given a matrix of N rows and M columns, the task is to sort the matrix in the strict order that is every row is sorted in increasing order and the first element of every row is greater than the first element of the previous row. Examples: Input: M[][] = { {5, 4, 7}, {1, 3, 8}, {2, 9, 6} } Output: 1 2 3 4 5 6 7 8 9 Explanation: Please refer above im
9 min read
How Data Structures can be used to achieve Efficient Memory Utilization
In the world of computer programming, using memory effectively is like fuelling a car efficiently. Similarly, in programming, memory is like the fuel that powers our software. Using memory wisely means making sure we don't waste it and use it for a purpose. To achieve efficient memory use, we use special tools called "data structures." These tools
12 min read
Reverse a singly Linked List in groups of given size | Set 4 (Space efficient approach)
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, k = 3Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, k = 5Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-&gt;8-&gt;
9 min read
Practice Tags :
three90RightbarBannerImg