Print Linked List Recursively

package org.wesome.dsalgo;

import lombok.Data;

import java.util.Objects;

public class LinkedList {
    static Node head;
    static int size = 0;


    static void addInLast(int element) {
        System.out.println("\nLinkedList.addInLast " + element);
        Node newNode = new Node(element);
        if (Objects.isNull(head)) {
            head = newNode;
            return;
        }
        Node tempNode = head;
        while (Objects.nonNull(tempNode.next)) {
            tempNode = tempNode.next;
        }
        tempNode.next = newNode;
        size++;
    }

    //this print the list using recursion
    static public void printRecursively(Node node) {
        if (Objects.isNull(node)) {
            return;
        }
        System.out.println(node.data + " ");
        printRecursively(node.next);
    }
}

@Data
class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.LinkedList.printRecursively;

public class LinkedListTest {
    @Test
    void printRecursivelyTest() {
        addInLast();
        printRecursively(LinkedList.head);
    }

    void addInLast() {
        LinkedList.addInLast(1);
        LinkedList.addInLast(2);
        LinkedList.addInLast(3);
        LinkedList.addInLast(4);
        LinkedList.addInLast(5);
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on