Double Linked List Program in Java

A double linked list is a node-based data structure. Each node built with three portions (Data Portion & Two Node Reference Portions).Almost all node reference may contain address/reference to connect another node if it really has neighbour nodes. The main purpose of using this data structure can travel in a bidirectional way.

[Download Source code]

DoubleLinkedList.java
1 package info.algonuts;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Iterator;
6 import java.util.List;
7
8 class DLLNode {
9 DLLNode leftChildNode;
10 int nodeValue;
11 DLLNode rightChildNode;
12
13 public DLLNode(int nodeValue) {
14 this.leftChildNode = null;
15 this.nodeValue = nodeValue;
16 this.rightChildNode = null;
17 }
18 }
19
20 class DLLCompute {
21 private static DLLNode newNode;
22 private static DLLNode headNode = null;
23 private static DLLNode tailNode;
24
25 private static DLLNode tempNode;
26
27 public static void add(int nodeValue) {
28 newNode = new DLLNode(nodeValue);
29 if(headNode != null) {
30 tempNode = headNode;
31 while(tempNode.rightChildNode != null) {
32 tempNode = tempNode.rightChildNode;
33 }
34 tempNode.rightChildNode = newNode;
35 newNode.leftChildNode = tempNode;
36 tailNode = newNode;
37 }
38 else
39 { headNode = newNode; }
40 }
41
42 public static void headIterator() {
43 System.out.println("Head Iterator:");
44 tempNode = headNode;
45 while(tempNode != null) {
46 System.out.print(tempNode.nodeValue+" ");
47 tempNode = tempNode.rightChildNode;
48 }
49 }
50
51 public static void tailIterator() {
52 System.out.println("Tail Iterator:");
53 tempNode = tailNode;
54 while(tempNode != null) {
55 System.out.print(tempNode.nodeValue+" ");
56 tempNode = tempNode.leftChildNode;
57 }
58 }
59 }
60
61 public class DoubleLinkedList {
62 //Entry Point
63 public static void main(String[] args) {
64 //First Set Input Values
65 List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));
66 Iterator<Integer> ptr = firstIntList.iterator();
67 while(ptr.hasNext())
68 { DLLCompute.add(ptr.next()); }
69 System.out.println("Iternation with First Set Values:");
70 DLLCompute.headIterator();
71 System.out.println("\n");
72 DLLCompute.tailIterator();
73 System.out.println("\n");
74
75 //Second Set Input Values
76 List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));
77 ptr = secondIntList.iterator();
78 while(ptr.hasNext())
79 { DLLCompute.add(ptr.next()); }
80 System.out.println("Iternation with First & Second Set Values:");
81 DLLCompute.headIterator();
82 System.out.println("\n");
83 DLLCompute.tailIterator();
84 }
85 }

0 Comments

Leave a Comment:

(Your email address will not be published. Required fields are marked *)

Name *

Email *

Message *

Social Media