Linked List Program in Java

A linked list is a node-based data structure. Each node designed with two portions (Data & Node Reference).Actually, data is always stored in Data portion (Maybe primitive data types eg Int, Float .etc or we can store user-defined data type also eg. Object reference) and similarly Node Reference should also contain the reference to next node, if there is no next node then the chain will end.

[Download Source code]

This chain will continue up to any node doesn't have a reference point to the next node.

LinkedList.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 LLNode {
9 int nodeValue;
10 LLNode childNode;
11
12 public LLNode(int nodeValue) {
13 this.nodeValue = nodeValue;
14 this.childNode = null;
15 }
16 }
17
18 class LLCompute {
19 private static LLNode newNode;
20 private static LLNode headNode = null;
21
22 private static LLNode tempNode;
23
24 public static void add(int nodeValue) {
25 newNode = new LLNode(nodeValue);
26 if(headNode != null) {
27 tempNode = headNode;
28 while(tempNode.childNode != null) {
29 tempNode = tempNode.childNode;
30 }
31 tempNode.childNode = newNode;
32 }
33 else
34 { headNode = newNode; }
35 }
36
37 public static void display() {
38 tempNode = headNode;
39 while(tempNode != null) {
40 System.out.print(tempNode.nodeValue+" ");
41 tempNode = tempNode.childNode;
42 }
43 }
44 }
45
46 public class LinkedList {
47 //Entry Point
48 public static void main(String[] args) {
49 //First Set Input Values
50 List <Integer> firstIntList = new ArrayList <Integer>(Arrays.asList(50,20,59,78,90,3,20,40,98));
51 Iterator<Integer> ptr = firstIntList.iterator();
52 while(ptr.hasNext())
53 { LLCompute.add(ptr.next()); }
54 System.out.println("Interation with First Set Values");
55 LLCompute.display();
56 System.out.println("\n");
57
58 //Second Set Input Values
59 List <Integer> secondIntList = new ArrayList <Integer>(Arrays.asList(1,5,8,100,91));
60 ptr = secondIntList.iterator();
61 while(ptr.hasNext())
62 { LLCompute.add(ptr.next()); }
63 System.out.println("Interation with First & Second Set Values");
64 LLCompute.display();
65 System.out.println();
66 }
67 }

0 Comments

Leave a Comment:

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

Name *

Email *

Message *

Social Media