Posts

Showing posts with the label Double Linked List

Deletion of entire Double linked list

Image
Simply, head = null; tail = null; will not work in case of Double Linked List. The reason for this is that, we have a previous node too, which will point to the previous node even if we make head=tail=null. So, the solution for this is that, we loop through the linked list and make all the prev=null (for each node.). Now, after this if we do head=tail=null, the entire linked list is deleted. Note : The nodes in any linked list is deleted one by one and not vanished all at once by garbage collection.

Double Linked List - All Operations

Image
  // The Double linked list node class Node{     int data;     Node next;     Node prev;          Node(int x){         this.data=x;         this.next=null;         this.prev=null;     } } public class Main {          // the head and tail of the linked list     Node head;     Node tail;          // function to add a new node to the last of linked list // Time Complexity - O(1), Space Complexity - O(1)     public void addNode(int x){         Node newNode = new Node(x);         // if linked list is empty         if(head==null){             head=newNode;             tail=newNode;       ...