I need HELP with the implementation of a double linked list in java

Hello Everyone ! I m currently studying linked lists in java . But i haven’t fully understood how the implementation of a double linked list works . So if anyone could show me how the implementation is done , could be great ! Thanks :smile:

For a doubly linked list, I guess you could create a Node class with the properties (instance fields) data, next, and previous.

Here’s one version (that stores integers as the .data) with lots of extra constructors:

one version ( Node2.java )
public class Node2 {

  public int data;
  public Node2 previous;
  public Node2 next;

  public Node2 (int d) {
    this.data = d;
    this.previous = null;
    this.next = null;
  }
  public Node2 (int d, Node2 nextNode) {
    this.data = d;
    this.next = nextNode;
    nextNode.previous = this;
    this.previous = null;
  }
  public Node2 (Node2 previousNode, int d) {
    this.data = d;
    this.previous = previousNode;
    previousNode.next = this;
    this.next = null;
  }
  public Node2 (Node2 previousNode, int d, Node2 nextNode) {
    this.data = d;
    this.previous = previousNode;
    previousNode.next = this;
    this.next = nextNode;
    nextNode.previous = this;
  }

  public void setNext(Node2 nextNode) {
    this.next = nextNode;
    nextNode.previous = this;
  }
  public void setNext(int nextData) {
    Node2 nextNode = new Node2(nextData);
    nextNode.previous = this;
  }
  public void setPrevious(Node2 previousNode) {
    this.previous = previousNode;
    previousNode.next = this;
  }
  public void setPrevious(int previousData) {
    Node2 previousNode = new Node2(previousData);
    previousNode.next = this;
  }

  public String toString() {
    String str = "";
    if (this.previous != null) {
      str += this.previous.data + "->";
    }
    str += "(" + this.data + ")";
    if (this.next != null) {
      str += "->" + this.next.data;
    }
    return str;
  }

  public static Node2 fromArray(int[] array) {
    int length = array.length;
    Node2 head;
    if (length < 1) {
      return null;
    }
    else {
      head = new Node2(array[0]);
    }
    Node2 previousNode = head;
    for (int i = 1; i < length; i++) {
      Node2 currentNode = new Node2(previousNode, array[i]);
      previousNode = currentNode;
    }
    return head;
  }

  public static void main(String[] args) {
    int[] intArray = {1, 2, 3, 4, 5};
    Node2 head = fromArray(intArray);
    System.out.println(head);
    Node2 node = head;
    while (node.next != null) {
      node = node.next;
      System.out.println(node);
    }
  }
}
1 Like

Thank you so much . It really helped !!