From 37bb532a28ee5369b18ccac413dae3660f66353a Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 1 Oct 2024 17:11:26 +0530 Subject: [PATCH] LinkedList added --- .../LinkedList/LinkedListTraversal.java | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 src/main/java/com/thealgorithms/LinkedList/LinkedListTraversal.java diff --git a/src/main/java/com/thealgorithms/LinkedList/LinkedListTraversal.java b/src/main/java/com/thealgorithms/LinkedList/LinkedListTraversal.java new file mode 100644 index 000000000000..2c1dc4e538ec --- /dev/null +++ b/src/main/java/com/thealgorithms/LinkedList/LinkedListTraversal.java @@ -0,0 +1,55 @@ +package com.thealgorithms.LinkedList; + +public class LinkedListTraversal { + + private static class Node{ + private int data; + private Node next; + + public Node(int data){ + this.data = data; + } + + public Node(){ + } + } + + private Node head; + + public Node addElement(int val,Node node){ + + Node newNode = new Node(val); + + if (node == null){ + node = newNode; + head = node; + return head; + } + + Node temp = node; + while(temp.next != null){ + temp = temp.next; + } + + temp.next = new Node(val); + return node; + } + + public void traverse(Node node){ + while (node != null){ + System.out.println(node.data); + node = node.next; + } + } + + public static void main(String[] args) { + int[] arr = {1,7,3,4}; + LinkedListTraversal linkedList = new LinkedListTraversal(); + Node node = new Node(); + for (int i = 0; i < arr.length; i++) { + node = linkedList.addElement(arr[i],node); + } + + linkedList.traverse(node.next); + } +}