Home Tools

Doubly Linked List - Java

A Double linked list is a linked data structure, it built like set of nodes and each node contain three portions (one Data portion & two Node Reference portions). Almost all Node References portion may connected to another node if it really had neighbor node or otherwise Reference portion marked as NULL. Data portion can store any primitive data types or user defined object.The main purpose of using this data structure can travel bidirectional.
DoublyLinkedList.java
1import java.util.Scanner;
2
3class DLLNode {
4	DLLNode parentNode;
5	int nodeValue;
6	DLLNode childNode;
7	
8	public DLLNode(int nodeValue) {
9		parentNode = null;
10		this.nodeValue = nodeValue;
11		childNode = null;
12	}
13}
14
15class DLLCompute {
16	private static DLLNode newNode;
17	private static DLLNode headNode = null;
18	private static DLLNode tailNode = null;
19	private static DLLNode tempNode;
20	
21	public static void add(int nodeValue) {
22		newNode = new DLLNode(nodeValue);
23		if(headNode != null) {
24			tailNode.childNode = newNode;
25			newNode.parentNode = tailNode;
26			tailNode = newNode;
27		}
28		else
29		{
30			headNode = newNode;
31			tailNode = newNode;
32		}
33	}
34	
35	public static void displayFromHead() {
36		tempNode = headNode;
37		if(tempNode != null) {
38			while(tempNode.childNode != null) {
39				System.out.print(tempNode.nodeValue+" ");
40				tempNode = tempNode.childNode;
41			}
42			System.out.println(tempNode.nodeValue);
43		}
44	}
45	
46	public static void displayFromTail() {
47		tempNode = tailNode;
48		if(tempNode != null) {
49			while(tempNode.parentNode != null) {
50				System.out.print(tempNode.nodeValue+" ");
51				tempNode = tempNode.parentNode;
52			}
53			System.out.println(tempNode.nodeValue);
54		}
55	}
56}
57
58public class DoublyLinkedList {
59	public static void main(String[] args) {
60		Scanner scan = new Scanner(System.in);
61        System.out.print("Enter the number of elements to insert:");
62        int numberOfElements = scan.nextInt();
63        int count = 1;
64        for(;count<=numberOfElements;count++) {
65        	System.out.print("Enter the "+count+" element value:"); 
66        	DLLCompute.add(scan.nextInt);
67        }
68        System.out.print("Show data's from Head Postition:");
69        DLLCompute.displayFromHead();
70        System.out.print("Show data's from Tail Postition:");
71        DLLCompute.displayFromTail();
72	}
73}

Output

Enter the number of elements to insert:5
Enter the 1 element value:43
Enter the 2 element value:2
Enter the 3 element value:53
Enter the 4 element value:5
Enter the 5 element value:78
Show data's from Head Postition:43 2 53 5 78
Show data's from Tail Postition:78 5 53 2 43