check if a linked list is a palindrome
/**
* palindrome
*/
public class palindrome {
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public static Node head;
public static Node tail;
public void addFirst(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
public void print() {
Node temp = head;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
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;
}
public boolean checkPalindrome() {
if (head == null || head.next != null) {
// FIND MID
Node midNode = findMid(head);
// REVERSE THE 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;
Node left = head;
while (right != null) {
if (left.data != right.data) {
return false;
}
left = left.next;
right = right.next;
}
}
return true;
}
public static void main(String[] args) {
Linkedlist ll = new Linkedlist();
ll.addFirst(1);
ll.addFirst(2);
ll.addFirst(2);
ll.addFirst(1);
ll.print();
System.out.println(ll.checkPalindrome());
}
}
Comments
Post a Comment