Linked List Add In First

package org.wesome.dsalgo;

import lombok.Data;

import java.util.Objects;

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

    static void addInFirst(int data) {
        System.out.println("\nLinkedList.addInFirst " + data);
        Node node = new Node(data);
        if (Objects.isNull(head)) {
            head = node;
        } else {
            node.next = head;
            head = node;
        }
        size++;
    }

    //this method print the list using loop
    static void printIteratively() {
        System.out.println("\nLinkedList.printIteratively");
        if (Objects.isNull(head)) {
            System.out.println("Linked List is null = " + head);
            return;
        }
        Node tempNode = head;
        System.out.println("Linked List Size is " + size);
        while (Objects.nonNull(tempNode)) {
            System.out.println("Node = " + tempNode.data);
            tempNode = tempNode.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;

public class LinkedListTest {
    @Test
    void addInFirstTest() {
        System.out.println("add in first");
        LinkedList.addInFirst(1);
        LinkedList.addInFirst(2);
        LinkedList.addInFirst(3);
        LinkedList.addInFirst(4);
        LinkedList.addInFirst(5);
        LinkedList.addInFirst(6);
        LinkedList.printIteratively();
    }
}
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