Linked List Nth-to-last Element

package org.wesome.dsalgo;

import lombok.Data;

import java.util.NoSuchElementException;
import java.util.Objects;

public class LinkedList {
    static Node head;

    static void print() {
        if (Objects.isNull(head)) {
            System.out.println("list is null = " + head);
            return;
        }
        Node tempNode = head;
        while (Objects.nonNull(tempNode)) {
            System.out.println("Node = " + tempNode.data);
            tempNode = tempNode.next;
        }
    }

    static void addInLast(int 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;
    }

    static public Node getNthToLastElement(int nth) {
        Node slow = head, fast = head;
        for (int i = 0; i < nth; i++) {
            if (Objects.isNull(fast)) {
                System.out.println("there is no element in list after " + i);
                throw new NoSuchElementException();
            }
            fast = fast.next;
        }
        while (Objects.nonNull(fast.next)) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }


    @Data
    static 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 addInLast() {
        LinkedList.addInLast(1);
        LinkedList.addInLast(2);
        LinkedList.addInLast(3);
        LinkedList.addInLast(4);
        LinkedList.addInLast(5);
        LinkedList.addInLast(6);
    }

    @Test
    void print() {
        LinkedList.print();
    }

    @Test
    void getNthToLastElement() {
        LinkedList.Node nthToLastElement = LinkedList.getNthToLastElement(2);
        System.out.println("nthToLastElement = " + nthToLastElement.data);
    }
}
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