package org.wesome.dsalgo;
import lombok.Data;
import java.util.Objects;
public class LinkedList {
static Node head;
static int size = 0;
//this method print the list using loop
static void printIteratively() {
System.out.println("LinkedList.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;
}
}
static void addInLast(int element) {
System.out.println("LinkedList.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++;
}
public static void rotateLinkedList(Node head, int degree) {
Node temp, tempHead = head, prev = head;
/* iterate till degree is not 0
* keep previous so that its next cal be null, else it will become looped Linked List
* tempHead will hold the start of LinkedList till degree, it will be appended at the end
* */
while (degree > 0 && Objects.nonNull(head) && Objects.nonNull(head.next)) {
prev = head;
head = head.next;
degree--;
}
/* this previous is the end of new rotated linked List now, make its next as null */
prev.next = null;
temp = head;
LinkedList.head = head;
/* iterate till end of linked list */
while (Objects.nonNull(temp) && Objects.nonNull(temp.next)) {
temp = temp.next;
}
/* append original head at the end of new rotated Linked List */
temp.next = tempHead;
}
}
@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.printIteratively;
public class LinkedListTest {
@Test
void rotateTest() {
addInLast();
printIteratively();
LinkedList.rotateLinkedList(LinkedList.head, 3);
printIteratively();
}
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()
}