October 20, 2020
How to create a linked list in java
A Linked list is a linked data structure, it built like set of nodes and each node contain two portions (Data portion & Node Reference portion).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 similiarly Node Reference portion may connected to another node if it really had neighbor node or otherwise Reference portion marked as NULL.LinkedList.java
1 import java.util.Scanner;
2
3 class LLNode {
4 int nodeValue;
5 LLNode childNode;
6
7 public LLNode(int nodeValue) {
8 this.nodeValue = nodeValue;
9 childNode = null;
10 }
11 }
12
13 class LLCompute {
14 private static LLNode newNode;
15 private static LLNode headNode = null;
16 private static LLNode tempNode;
17
18 public static void add(int nodeValue) {
19 newNode = new LLNode(nodeValue);
20 if(headNode != null) {
21 tempNode = headNode;
22 while(tempNode.childNode != null) {
23 tempNode = tempNode.childNode;
24 }
25 tempNode.childNode = newNode;
26 }
27 else
28 {
29 headNode = newNode;
30 }
31 }
32
33 public static void display() {
34 tempNode = headNode;
35 if(tempNode != null) {
36 while(tempNode.childNode != null) {
37 System.out.print(tempNode.nodeValue+" ");
38 tempNode = tempNode.childNode;
39 }
40 System.out.println(tempNode.nodeValue);
41 }
42 }
43 }
44
45 public class LinkedList {
46 public static void main(String[] args) {
47 Scanner scan = new Scanner(System.in);
48 System.out.print("Enter the number of elements to insert:");
49 int numberOfElements = scan.nextInt();
50 int count = 1;
51 for(;count<=numberOfElements;count++) {
52 System.out.print("Enter the "+count+" element value:");
53 LLCompute.add(scan.nextInt());
54 }
55 LLCompute.display();
56 }
57 }
No comments:
Post a Comment