Solution: Find If a Doubly Linked List Is a Palindrome
Let’s solve the Find If a Doubly Linked List Is a Palindrome problem.
We'll cover the following
Statement
Given the head of a doubly linked list, check whether the doubly linked list is a palindrome or not. Return TRUE if it is a palindrome; otherwise, return FALSE.
A palindrome is any string or sequence that reads the same from both ends. For example, 2002 is a palindrome.
Constraints:
Let n
be the number of nodes in a doubly linked list.
Solution
To determine whether a doubly linked list is a palindrome, we start by setting up two pointers: one at the beginning and one at the end of the list. It's easier to set the pointer at the head of the given linked list but to set it to the tail of the linked list requires traversing the entire list until we find a node whose next pointer is NULL. Having the pointers at these positions allows us to compare elements from both ends simultaneously. We compare the elements pointed to by the start and end pointers and proceed as follows:
If the elements don't match, it indicates that the list cannot be a palindrome, so we return FALSE.
If the elements match, we increment the start pointer forward and decrement the end pointer backward, effectively traversing the list towards the center.
This process continues until either the two pointers meet (in the case of odd-length lists) or until they cross each other (in the case of even-length lists). In both cases, we've checked the entire list without finding any mismatches, which means the list is a palindrome. Therefore, we return TRUE.
Conversely, if we encounter a pair of elements that don't match at any point, we can return FALSE indicating that the list is not a palindrome.
Note: If the list is empty, we can consider it a palindrome since there are no elements to compare.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.