Doubly Linked list in java

               Doubly linked list – A linked list has two pointers and one data in the node.first pointer points the previous node. Second pointer points the next node.

Let us create the doubly linked list in java.

Java implementation of DoublyLinkedList :

To implement the doubly linked list, follow the steps.

Steps:

  • First, create a class “DoublyLinkedListEg”
  • A class ‘node’ with member variables and functions are created.
  • Member variables:
  • ‘data’ as integer.
  • ‘next_ptr’,’prev_ptr’ as self referential variables.
  • Constructor ‘Node(int data)’: It initialises the variables.
  • Create a ‘head’ node.
  • ‘insert()’ -it adds the data to doubly linked list.
  •  Create a newnode.
  • If head is null, assign the newnode as head.
  • Otherwise, create a temp node. Find the place to add the data. Assign the prev_ptr and next_ptr according to it.
  • ‘display()’:
  • This function shows the data elements in the screen.
  • ‘main()’:
  •  It creates the object for DoublyLinkedListEg and calls the functions ‘insert()’ and ‘display()’.

Program:

class DoublyLinkedListEg {

    class Node {

        int data;

        Node next_ptr;

        Node prev_ptr;

        Node(int data) {

            this.data = data;

            this.next_ptr = null;

            this.prev_ptr = null;

        }

    }

    Node head;

    public void insert(int data) {

        Node newNode = new Node(data);

        if (head == null) {

            head = newNode;

        } else {

            Node temp = head;

            while (temp.next_ptr != null) {

                temp = temp.next_ptr;

            }

            temp.next_ptr = newNode;

            newNode.prev_ptr = temp;

        }

    }

    public void display() {

        Node temp = head;

        while (temp != null) {

            System.out.print(temp.data + " <-> ");

            temp = temp.next_ptr;

        }

        System.out.println("null");

    }

    public static void main(String[] args) {

        DoublyLinkedListEg d1 = new DoublyLinkedListEg();

        // Insert the elements to doubly linked list

        d1.insert(90);

        d1.insert(120);

        d1.insert(230);

        d1.insert(430);

        d1.insert(520);

        // Display the list of elements in doubly linked list

        System.out.println("Doubly Linked List data elements:");

        d1.display();

    }

}

Here, is the output.

C:\raji\blog>javac DoublyLinkedListEg.java

C:\raji\blog>java DoublyLinkedListEg

Doubly Linked List data elements:

90 <-> 120 <-> 230 <-> 430 <-> 520 <-> null

This is the doubly linked list created by java. Hope this code is useful to you. Keep coding!!!

No comments:

Post a Comment