Given a singly linked list of integers, determine whether the linked list is a palindrome.

For example,

Input:  1 —> 2 —> 3 —> 2 —> 1 —> null
Output: Linked list is a palindrome
 
 
Input:  1 —> 2 —> 3 —> 3 —> 1 —> null
Output: Linked list is not a palindrome

Practice this problem

The idea is to traverse the linked list and push all encountered elements into a stack. Then traverse the linked list again, and for each node, pop the top element from the stack and compare it with the node’s data. If a mismatch happens for any node, we can say that the linked list is not a palindrome.

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

C++


Download  Run Code

Output:

Linked List is a palindrome.

Java


Download  Run Code

Output:

Linked List is a palindrome.

Python


Download  Run Code

Output:

Linked List is a palindrome.

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list. The auxiliary space required by the solution is O(n) for the stack container.

 
We can determine whether a linked list is a palindrome in linear time and with constant space. The idea is to split the given list into two halves and reverse the second half. Then traverse both lists simultaneously and compare their data. If a mismatch happens for any node, we can say that the linked list is not a palindrome.

The implementation can be seen below in C++, Java, and Python. Since the solution modifies the given list, we need to restore the original linked list. We can do this by simply linking the first half with the second half.

C++


Download  Run Code

Output:

Linked List is a palindrome.

Java


Download  Run Code

Output:

Linked List is a palindrome.

Python


Download  Run Code

Output:

Linked List is a palindrome.

We can avoid modification of the original list (even temporarily) with the power of recursion. Following is the simple C++, Java, and Python recursive implementation that works by recursing till the end of the list and checking each node of the linked list for palindrome as the recursion unfolds:

C++


Download  Run Code

Output:

Linked list is a palindrome.

Java


Download  Run Code

Output:

Linked list is a palindrome.

Python


Download  Run Code

Output:

Linked list is a palindrome