Given a linked list, check if it is a palindrome or not.

Practice this problem

A simple solution would be to create a clone of the linked list, reverse it, and check if both linked lists are equal or not. This approach requires three traversals of the linked list and requires extra space for storing duplicates.

 
A better solution is to use recursion. The idea is to reach the end of the linked list by recursion and then compare if the last node has the same value as the first node and the second previous node has the same value as the second node, and so on using the call stack and a pointer at the beginning of the linked list.

Following is the C, Java, and Python implementation of the idea:

C


Download  Run Code

Output:

The linked list is a palindrome

Java


Download  Run Code

Output:

The linked list is a palindrome

Python


Download  Run Code

Output:

The linked list is a palindrome

The time complexity of the above solution is O(n), where n is the length of the linked list. The auxiliary space required by the program for the call stack is proportional to the lists’ length.

 
We can solve this problem in constant space and linear time by dividing the problem into three subproblems:

  • Divide the list into two equal parts.
  • Reverse the second half.
  • Check if the first and second half is similar. If the linked list contains an odd number of nodes, then ignore the middle element.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The linked list is a palindrome

Java


Download  Run Code

Output:

The linked list is a palindrome

Python


Download  Run Code

Output:

The linked list is a palindrome