Open In App

Javascript Program To Check If A Singly Linked List Is Palindrome

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.

Palindrome Linked List

METHOD 1 (Use a Stack) 

  • A simple solution is to use a stack of list nodes. This mainly involves three steps.
  • Traverse the given list from head to tail and push every visited node to stack.
  • Traverse the list again. For every visited node, pop a node from the stack and compare data of popped node with the currently visited node.
  • If all nodes matched, then return true, else false.

Below image is a dry run of the above approach: 

Below is the implementation of the above approach : 

Javascript




<script>
// JavaScript program to check if
// linked list is palindrome recursively
class Node
{
    constructor(val)
    {
        this.data = val;
        this.ptr = null;
    }
}
     
var one = new Node(1);
var two = new Node(2);
var three = new Node(3);
var four = new Node(4);
var five = new Node(3);
var six = new Node(2);
var seven = new Node(1);
one.ptr = two;
two.ptr = three;
three.ptr = four;
four.ptr = five;
five.ptr = six;
six.ptr = seven;
var condition = isPalindrome(one);
document.write("isPalidrome: " + condition);
     
function isPalindrome(head)
{
    var slow = head;
    var ispalin = true;
    var stack = [];
 
    while (slow != null)
    {
        stack.push(slow.data);
        slow = slow.ptr;
    }
 
    while (head != null)
    {
        var i = stack.pop();
        if (head.data == i)
        {
            ispalin = true;
        }
        else
        {
            ispalin = false;
            break;
        }
        head = head.ptr;
    }
    return ispalin;
}
// This code is contributed by todaysgaurav
</script>


Output: 

 isPalindrome: true

Time complexity: O(n), where n represents the length of the given linked list.

Auxiliary Space: O(n), for using a stack, where n represents the length of the given linked list.

METHOD 2 (By reversing the list): 
This method takes O(n) time and O(1) extra space. 
1) Get the middle of the linked list. 
2) Reverse the second half of the linked list. 
3) Check if the first half and second half are identical. 
4) Construct the original linked list by reversing the second half again and attaching it back to the first half

To divide the list into two halves, method 2 of this post is used. 

When a number of nodes are even, the first and second half contains exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’. 

Javascript




<script>
// Javascript program to check if
// linked list is palindrome
 
// Head of list
var head;
var slow_ptr,
    fast_ptr, second_half;
 
// Linked list Node
class Node
{
    constructor(val)
    {
        this.data = val;
        this.next = null;
    }
}
 
// Function to check if given linked list
// is palindrome or not
function isPalindrome(head)
{
    slow_ptr = head;
    fast_ptr = head;
    var prev_of_slow_ptr = head;
 
    // To handle odd size list
    var midnode = null;
 
    // Initialize result
    var res = true;
 
    if (head != null &&
        head.next != null)
    {
        // Get the middle of the list.
        // Move slow_ptr by 1 and fast_ptrr
        // by 2, slow_ptr will have the middle node
        while (fast_ptr != null &&
               fast_ptr.next != null)
        {
            fast_ptr = fast_ptr.next.next;
 
            // We need previous of the slow_ptr for
            //  linked lists with odd elements
            prev_of_slow_ptr = slow_ptr;
            slow_ptr = slow_ptr.next;
        }
         
        // fast_ptr would become NULL when there are
        // even elements in the list and not NULL for
        // odd elements. We need to skip the middle
        // node for odd case and store it somewhere
        // so that we can restore the original list        
        if (fast_ptr != null)
        {
            midnode = slow_ptr;
            slow_ptr = slow_ptr.next;
        }
 
        // Now reverse the second half and
        // compare it with first half
        second_half = slow_ptr;
 
        // NULL terminate first half
        prev_of_slow_ptr.next = null;
   
        // Reverse the second half
        reverse();
 
        // compare
        res = compareLists(head, second_half);
 
        // Construct the original list back
        // Reverse the second half again
        reverse();
 
        if (midnode != null)
        {
            // If there was a mid node (odd size case)
            // which was not part of either first half
            // or second half.
            prev_of_slow_ptr.next = midnode;
            midnode.next = second_half;
         }
         else
             prev_of_slow_ptr.next = second_half;
    }
    return res;
}
 
// Function to reverse the linked list.
// Note that this function may change the
// head
function reverse()
{
    var prev = null;
    var current = second_half;
    var next;
    while (current != null)
    {
        next = current.next;
        current.next = prev;
        prev = current;
        current = next;
    }
    second_half = prev;
}
 
// Function to check if two input
// lists have same data
function compareLists(head1, head2)
{
    var temp1 = head1;
    var temp2 = head2;
 
    while (temp1 != null &&
           temp2 != null)
    {
        if (temp1.data == temp2.data)
        {
            temp1 = temp1.next;
            temp2 = temp2.next;
        }
        else
            return false;
    }
 
    // Both are empty return 1
    if (temp1 == null &&
        temp2 == null)
        return true;
 
    //Will reach here when one is NULL
    //  and other is not
    return false;
}
 
// Push a node to the linked list.
// Note that this function changes the head
function push(new_data)
{
    // Allocate the Node & Put in the data
    var new_node = new Node(new_data);
 
    // link the old list of the new one
    new_node.next = head;
 
    // Move the head to point to new Node
    head = new_node;
}
 
// A utility function to point a
// given linked list
function printList(ptr)
{
    while (ptr != null)
    {
        document.write(ptr.data + "->");
        ptr = ptr.next;
    }
        document.write("NULL<br/>");
}
 
// Driver code
 
// Start with the empty list
var str = ['a', 'b', 'a',
           'c', 'a', 'b', 'a'];
var string = str.toString();
         
for (i = 0; i < 7; i++)
{
    push(str[i]);
    printList(head);
    if (isPalindrome(head) != false)
    {
        document.write("Is Palindrome");
        document.write("<br/>");
    }
    else
    {
        document.write("Not Palindrome");
        document.write("<br/>");
    }
}
// This code is contributed by gauravrajput1
</script>


Output: 

a->NULL
Is Palindrome

b->a->NULL
Not Palindrome

a->b->a->NULL
Is Palindrome

c->a->b->a->NULL
Not Palindrome

a->c->a->b->a->NULL
Not Palindrome

b->a->c->a->b->a->NULL
Not Palindrome

a->b->a->c->a->b->a->NULL
Is Palindrome

Time Complexity: O(n) 
Auxiliary Space: O(1)  

METHOD 3 (Using Recursion): 
Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 
1) Sub-list is a palindrome. 
2) Value at current left and right are matching.

If both above conditions are true then return true.

The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list.

In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.
However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.
Thanks to Sharad Chandra for suggesting this approach.

Javascript




<script>
// Javascript program to implement
// the above approach
 
// Head of the list
var head;
var left;
 
class Node
{
    constructor(val)
    {
        this.data = val;
        this.next = null;
    }
}
 
// Initial parameters to this function
// are &head and head
function isPalindromeUtil(right)
{
    left = head;
 
    // Stop recursion when right
    // becomes null
    if (right == null)
        return true;
 
    // If sub-list is not palindrome then
    // no need to check for the current
    // left and right, return false
    var isp = isPalindromeUtil(right.next);
    if (isp == false)
        return false;
 
    // Check values at current left and right
    var isp1 = (right.data == left.data);
 
    left = left.next;
 
    // Move left to next node;
    return isp1;
}
 
// A wrapper over isPalindrome(Node head)
function isPalindrome(head)
{
    var result = isPalindromeUtil(head);
    return result;
}
 
// Push a node to linked list.
// Note that this function changes
// the head
function push(new_data)
{
    // Allocate the node and
    //  put in the data
    var new_node = new Node(new_data);
 
    // Link the old list of the
    // the new one
    new_node.next = head;
 
    // Move the head to point to new node
    head = new_node;
}
 
// A utility function to point a
// given linked list
function printList(ptr)
{
    while (ptr != null)
    {
        document.write(ptr.data + "->");
        ptr = ptr.next;
    }
    document.write("Null ");
    document.write("<br>");
 
}
 
// Driver Code
var str = ['a', 'b', 'a',
           'c', 'a', 'b', 'a'];
for (var i = 0; i < 7; i++)
{
    push(str[i]);
    printList(head);
 
     if (isPalindrome(head))
     {
         document.write("Is Palindrome");
         document.write("<br/>");
         document.write("<br>");
     }
     else
     {
         document.write("Not Palindrome");
         document.write("<br/>");
         document.write("<br/>");
     }
}
// This code is contributed by aashish1995
/script>


Output: 

a->NULL
Not Palindrome

b->a->NULL
Not Palindrome

a->b->a->NULL
Is Palindrome

c->a->b->a->NULL
Not Palindrome

a->c->a->b->a->NULL
Not Palindrome

b->a->c->a->b->a->NULL
Not Palindrome

a->b->a->c->a->b->a->NULL
Is Palindrome

Time Complexity: O(n) 
Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1).

Please refer complete article on Function to check if a singly linked list is palindrome for more details!
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads