Approach 1 :
1) Reach till middle of list;
2) Reverse from middle till last
3) compare & return
var isPalindrome = function(head) {
const midElementOfList = getMiddleElemnt(head);
const reversedFromMiddleTillEnd = reverseList(midElementOfList);
return checkIfPalindrome(head, reversedFromMiddleTillEnd);
};
var getMiddleElemnt = (head) => {
let slow = head;
let fast = head;
while(fast && fast.next !==null && fast.next.next !== null){
slow = slow.next;
fast= fast.next.next;
}
return slow;
}
var checkIfPalindrome = (head, reverseList) =>{
while(head!==null && reverseList !==null){
if(head.val!== reverseList.val){
return false;
}
head = head.next;
reverseList= reverseList.next;
}
return true;
}
var reverseList = function(head) {
const reverseR = (head) => {
if (head === null || head.next === null) {
return head;
}
let rest_trail = reverseR(head.next);
const nextOfHead = head.next;
nextOfHead.next = head;
head.next = null;
return rest_trail;
}
return reverseR(head);
}
Approach 2 :
1) Reach till end of list & store value of each node in array.
2) Now Reverse array & compare each element with actual array.
Approach 3 :
1) Clone out List first - (Add's complexity & extra work)
1) Now Reverse cloned List
2) Compare each element with actual List.