class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
public void printList() {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// helper function to find middle
public Node findMid(Node head) {
Node slow = head;
Node fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
// check if linked list is palindrome
public boolean checkPalindrome() {
if (head == null || head.next == null) {
return true;
}
// step1: find mid
Node midNode = findMid(head);
// step2: reverse 2nd half
Node prev = null;
Node curr = midNode;
Node next;
while (curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
Node right = prev; // head of reversed half
Node left = head;
// step3: check both halves
while (right != null) {
if (left.data != right.data) {
return false;
}
left = left.next;
right = right.next;
}
return true;
}
}
public class Main {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(1);
ll.add(2);
ll.add(1);
// ll.add(1);
ll.printList(); // ✅ print list
System.out.println(ll.checkPalindrome()); // ✅ true
}
}
No comments:
Post a Comment