C++ Program To Check If A Singly Linked List Is Palindrome
Last Updated :
11 Apr, 2023
Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false.

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 :
C++
// C++ program to implement
// the above approach
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node(int d)
{
data = d;
}
Node *ptr;
};
// Function to check if the linked list
// is palindrome or not
bool isPalin(Node* head)
{
// Temp pointer
Node* slow= head;
// Declare a stack
stack <int> s;
// Push all elements of the list
// to the stack
while(slow != NULL)
{
s.push(slow->data);
// Move ahead
slow = slow->ptr;
}
// Iterate in the list again and
// check by popping from the stack
while(head != NULL )
{
// Get the top most element
int i=s.top();
// Pop the element
s.pop();
// Check if data is not
// same as popped element
if(head -> data != i)
{
return false;
}
// Move ahead
head=head->ptr;
}
return true;
}
// Driver Code
int main()
{
// Addition of linked list
Node one = Node(1);
Node two = Node(2);
Node three = Node(3);
Node four = Node(2);
Node five = Node(1);
// Initialize the next pointer
// of every current pointer
five.ptr = NULL;
one.ptr = &two;
two.ptr = &three;
three.ptr = &four;
four.ptr = &five;
Node* temp = &one;
// Call function to check
// palindrome or not
int result = isPalin(&one);
if(result == 1)
cout << "isPalindrome is true";
else
cout << "isPalindrome is true";
return 0;
}
// This code has been contributed by Striver
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'.
C++
// C++ program to check if a linked list
// is palindrome
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node
{
char data;
struct Node* next;
};
void reverse(struct Node**);
bool compareLists(struct Node*,
struct Node*);
// Function to check if given linked list
// is palindrome or not
bool isPalindrome(struct Node* head)
{
struct Node *slow_ptr = head,
*fast_ptr = head;
struct Node *second_half,
*prev_of_slow_ptr = head;
// To handle odd size list
struct Node* midnode = NULL;
// initialize result
bool 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 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(&second_half);
// compare
res = compareLists(head, second_half);
// Construct the original list back
// Reverse the second half again
reverse(&second_half);
// If there was a mid node (odd size case)
// which was not part of either first half
// or second half.
if (midnode != NULL)
{
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
void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
// Function to check if two input
// lists have same data
bool compareLists(struct Node* head1,
struct Node* head2)
{
struct Node* temp1 = head1;
struct Node* temp2 = head2;
while (temp1 && temp2)
{
if (temp1->data == temp2->data)
{
temp1 = temp1->next;
temp2 = temp2->next;
}
else
return 0;
}
// Both are empty return 1
if (temp1 == NULL && temp2 == NULL)
return 1;
// Will reach here when one is NULL
// and other is not
return 0;
}
// Push a node to linked list. Note
// that this function changes the head
void push(struct Node** head_ref,
char new_data)
{
// Allocate node
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
// Put in the data
new_node->data = new_data;
// Link the old list of the new node
new_node->next = (*head_ref);
// Move the head to point to the new node
(*head_ref) = new_node;
}
// A utility function to print a
// given linked list
void printList(struct Node* ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL" << "";
}
// Driver code
int main()
{
// Start with the empty list
struct Node* head = NULL;
char str[] = "abacaba";
int i;
for(i = 0; str[i] != ''; i++)
{
push(&head, str[i]);
printList(head);
isPalindrome(head) ? cout << "Is Palindrome" <<
"" : cout << "Not Palindrome" << "";
}
return 0;
}
// This code is contributed by Shivani
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 list. When we return from last NULL, we will be at the last node. The last node to be compared with first node of list.
In order to access first node of list, we need 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 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.
C++
// Recursive program to check if a given
// linked list is palindrome
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct node
{
char data;
struct node* next;
};
// Initial parameters to this function
// are &head and head
bool isPalindromeUtil(struct node** left,
struct node* right)
{
// Stop recursion when right
// becomes NULL
if (right == NULL)
return true;
/* If sub-list is not palindrome then no
need to check for current left and right,
return false */
bool isp = isPalindromeUtil(left,
right->next);
if (isp == false)
return false;
// Check values at current left and right
bool isp1 = (right->data == (*left)->data);
// Move left to next node
*left = (*left)->next;
return isp1;
}
// A wrapper over isPalindromeUtil()
bool isPalindrome(struct node* head)
{
isPalindromeUtil(&head, head);
}
/* Push a node to linked list. Note that
this function changes the head */
void push(struct node** head_ref,
char new_data)
{
// Allocate node
struct node* new_node =
(struct node*)malloc(sizeof(struct node));
// Put in the data
new_node->data = new_data;
// Link the old list of the new node
new_node->next = (*head_ref);
// Move the head to point to the new node
(*head_ref) = new_node;
}
// A utility function to print a
// given linked list
void printList(struct node* ptr)
{
while (ptr != NULL)
{
cout << ptr->data << "->";
ptr = ptr->next;
}
cout << "NULL" ;
}
// Driver code
int main()
{
// Start with the empty list
struct node* head = NULL;
char str[] = "abacaba";
int i;
for (i = 0; str[i] != ''; i++)
{
push(&head, str[i]);
printList(head);
isPalindrome(head) ? cout <<
"Is Palindrome" : cout << "Not Palindrome";
}
return 0;
}
// This code is contributed by shivanisinghss2110
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!
Similar Reads
C++ Program to Check if a Given String is Palindrome or Not
A string is said to be palindrome if the reverse of the string is the same as the original string. In this article, we will check whether the given string is palindrome or not in C++.ExamplesInput: str = "ABCDCBA"Output: "ABCDCBA" is palindromeExplanation: Reverse of the string str is "ABCDCBA". So,
4 min read
C++ Program For Checking Linked List With A Loop Is Palindrome Or Not
Given a linked list with a loop, the task is to find whether it is palindrome or not. You are not allowed to remove the loop. Examples: Input: 1 -> 2 -> 3 -> 2 /| |/ ------- 1 Output: Palindrome Linked list is 1 2 3 2 1 which is a palindrome. Input: 1 -> 2 -> 3 -> 4 /| |/ ------- 1
5 min read
Program to check if an Array is Palindrome or not using STL in C++
Given an array, the task is to determine whether an array is a palindrome or not, using STL in C++. Examples: Input: arr[] = {3, 6, 0, 6, 3} Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5} Output: Not Palindrome Approach: Get the reverse of the Array using reverse() method, provided in STL.Initial
2 min read
Recursive program to check if number is palindrome or not
Given a number, the task is to write a recursive function that checks if the given number is a palindrome or not. Examples: Input: 121Output: yes Input: 532Output: no The approach for writing the function is to call the function recursively till the number is wholly traversed from the back. Use a te
4 min read
C++ Program To Check If Two Linked Lists Are Identical
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE
3 min read
C++ Program to Check Whether a Number is Palindrome or Not
A palindrome number is a number that remains the same even if its digits are reversed. In this article, we will learn how to check a given number is a palindrome or not in C++.The easiest way to check if a number is a palindrome is to simply reverse the original number, then check if both numbers ar
4 min read
C++ Program For Detecting Loop In A Linked List
Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. The following are different ways of doing this. Solution 1: Hashing Approach: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reach
11 min read
C++ Program For Rearranging A Given Linked List In-Place
Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
7 min read
C++ Program For Segregating Even And Odd Nodes In A Linked List
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers the same. Examples: Input: 17->15->8->12->10->5->4->1->7->6-
7 min read
C++ Program To Find Minimum Insertions To Form A Palindrome | DP-28
Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Before we go further, let us understand with a few examples: ab: Number of insertions required is 1 i.e. babaa: Number of insertions required is 0 i.e. aaabcd: Number of insertions re
9 min read