Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Solution should be different for odd and even length

Aditya Verma

Nov 13, 2023

For add length the code might not work. Correct solution is: package com.techsavvy;

public class PalindromeLinkedlIst {

public static void main(String[] args) {

	ListNode head = new ListNode(2);

	head.next = new ListNode(4);

	head.next.next = new ListNode(6);

	head.next.next.next = new ListNode(8);

	head.next.next.next.next = new ListNode(6);

	head.next.next.next.next.next = new ListNode(4);

	head.next.next.next.next.next.next = new ListNode(2);

	if(*isPalindome*(head)) {

		System.*out*.println("Given List is Palindrome");

	} else {

		System.*out*.println("Given list is not a Palindrome");

	}

}



private static int length(ListNode head) {

	int count = 0;

	while(head != null) {

		head = head.next;

		count++;

	}

	return count;

}



private static boolean isPalindome(ListNode head) {

	int length = *length*(head);

	ListNode curr = head;

	ListNode middle = *findMiddleNode*(head);

	ListNode temp = null;

	if(length%2 == 0) {

		temp = *reverseLinkList*(middle);

	} else {

		temp = *reverseLinkList*(middle.next);

	}

	

	while(temp != null){

		if(curr.value != temp.value) {

			return false;

		}

		temp = temp.next;

		curr = curr.next;

	} 

	return true;

}



private static ListNode reverseLinkList(ListNode middle) {

	ListNode curr = middle;

	ListNode next = null;

	ListNode prev = null;

	while(curr != null) {

		next = curr.next;

		curr.next = prev;

		prev = curr;

		curr = next;

	}

	return prev;

}



private static ListNode findMiddleNode(ListNode head) {

	ListNode fast = head;

	ListNode slow = head;

	while(fast != null && fast.next != null) {

		fast = fast.next.next;

		slow = slow.next;

	}

	return slow;

}

}

class ListNode{

int value = 0;

ListNode next;

ListNode(int value){

	this.value = value;

}

}

1

1

Comments
Comments

On this page