package org.wesome.dsalgo;
import lombok.Data;
import java.util.Objects;
import java.util.Stack;
public class LinkedList {
static Node head;
static int size = 0;
static boolean palindrome() {
System.out.println("LinkedList.palindrome");
Node slow = head;
Node fast = head;
Stack<Integer> stack = new Stack<>();
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
if (stack.pop().intValue() != slow.data) {
System.out.println("LinkedList is not palindrome");
return false;
}
slow = slow.next;
}
System.out.println("LinkedList is palindrome");
return true;
}
//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++;
}
}
@Data
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.wesome.dsalgo.LinkedList.printIteratively;
public class LinkedListTest {
@Test
void palindromeTest() {
addInLast();
printIteratively();
Assertions.assertTrue(LinkedList.palindrome());
}
void addInLast() {
LinkedList.addInLast(1);
LinkedList.addInLast(2);
LinkedList.addInLast(3);
LinkedList.addInLast(3);
LinkedList.addInLast(2);
LinkedList.addInLast(1);
}
}
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()
}