File tree 1 file changed +55
-0
lines changed
src/main/java/com/thealgorithms/LinkedList
1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .thealgorithms .LinkedList ;
2
+
3
+ public class LinkedListTraversal {
4
+
5
+ private static class Node {
6
+ private int data ;
7
+ private Node next ;
8
+
9
+ public Node (int data ){
10
+ this .data = data ;
11
+ }
12
+
13
+ public Node (){
14
+ }
15
+ }
16
+
17
+ private Node head ;
18
+
19
+ public Node addElement (int val ,Node node ){
20
+
21
+ Node newNode = new Node (val );
22
+
23
+ if (node == null ){
24
+ node = newNode ;
25
+ head = node ;
26
+ return head ;
27
+ }
28
+
29
+ Node temp = node ;
30
+ while (temp .next != null ){
31
+ temp = temp .next ;
32
+ }
33
+
34
+ temp .next = new Node (val );
35
+ return node ;
36
+ }
37
+
38
+ public void traverse (Node node ){
39
+ while (node != null ){
40
+ System .out .println (node .data );
41
+ node = node .next ;
42
+ }
43
+ }
44
+
45
+ public static void main (String [] args ) {
46
+ int [] arr = {1 ,7 ,3 ,4 };
47
+ LinkedListTraversal linkedList = new LinkedListTraversal ();
48
+ Node node = new Node ();
49
+ for (int i = 0 ; i < arr .length ; i ++) {
50
+ node = linkedList .addElement (arr [i ],node );
51
+ }
52
+
53
+ linkedList .traverse (node .next );
54
+ }
55
+ }
You can’t perform that action at this time.
0 commit comments