<script>
class GfG{
class Node
{
constructor()
{
this
.data = 0;
this
.next =
null
;
}
}
function
getLoopstart(loop_node, head)
{
var
ptr1 = loop_node;
var
ptr2 = loop_node;
var
k = 1, i;
while
(ptr1.next != ptr2)
{
ptr1 = ptr1.next;
k++;
}
ptr1 = head;
ptr2 = head;
for
(i = 0; i < k; i++)
ptr2 = ptr2.next;
while
(ptr2 != ptr1)
{
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
return
ptr1;
}
function
detectAndgetLoopstarting(head)
{
var
slow_p = head, fast_p = head,
loop_start =
null
;
while
(slow_p !=
null
&& fast_p !=
null
&&
fast_p.next !=
null
)
{
slow_p = slow_p.next;
fast_p = fast_p.next.next;
if
(slow_p == fast_p)
{
loop_start = getLoopstart(slow_p, head);
break
;
}
}
return
loop_start;
}
function
isPalindromeUtil(head, loop_start)
{
var
ptr = head;
var
s = [];
var
count = 0;
while
(ptr != loop_start ||
count != 1)
{
s.push(ptr.data);
if
(ptr == loop_start)
count = 1;
ptr = ptr.next;
}
ptr = head;
count = 0;
while
(ptr != loop_start ||
count != 1)
{
var
stk = s.pop();
if
(ptr.data == stk);
else
{
s.push(stk);
return
false
;
}
if
(ptr == loop_start)
count = 1;
ptr = ptr.next;
}
return
true
;
}
function
isPalindrome(head)
{
var
loop_start =
detectAndgetLoopstarting(head);
return
isPalindromeUtil(head,
loop_start);
}
function
newNode(key)
{
var
temp =
new
Node();
temp.data = key;
temp.next =
null
;
return
temp;
}
var
head = newNode(50);
head.next = newNode(20);
head.next.next = newNode(15);
head.next.next.next = newNode(20);
head.next.next.next.next =
newNode(50);
head.next.next.next.next.next =
head.next.next;
if
(isPalindrome(head) ==
true
)
document.write(
"Palindrome"
);
else
document.write(
"Not Palindrome"
);
</script>