Tutorialspoint
Problem
Solution
Submissions

Palindrome Linked List

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to determine if a singly linked list is a palindrome. A palindrome is a sequence that reads the same forward and backward. For example, "racecar" is a palindrome. For a linked list, we need to check if the sequence of values from the first node to the last node reads the same as the sequence from the last node to the first node.

Example 1
  • Input: head = [1,2,2,1]
  • Output: true
  • Explanation:
    • Step 1: The linked list contains values [1,2,2,1]
    • Step 2: Reading from left to right: 1 -> 2 -> 2 -> 1
    • Step 3: Reading from right to left: 1 -> 2 -> 2 -> 1
    • Step 4: Both sequences are identical
    • Step 5: Therefore, the linked list is a palindrome
Example 2
  • Input: head = [1,2]
  • Output: false
  • Explanation:
    • Step 1: The linked list contains values [1,2]
    • Step 2: Reading from left to right: 1 -> 2
    • Step 3: Reading from right to left: 2 -> 1
    • Step 4: The sequences are different
    • Step 5: Therefore, the linked list is not a palindrome
Constraints
  • The number of nodes in the list is in the range [1, 10^5]
  • 0 <= Node.val <= 9
  • Time Complexity: O(n) where n is the number of nodes in the linked list
  • Space Complexity: O(1)
Linked ListTutorialspointAccenture
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • A naive approach would be to copy all values into an array and check if the array is a palindrome, but that would require O(n) extra space
  • To achieve O(1) space complexity, consider modifying the list structure temporarily
  • Find the middle of the linked list using slow and fast pointers
  • Reverse the second half of the linked list
  • Compare the first half with the reversed second half
  • Optionally, restore the list to its original structure

Steps to solve by this approach:

 Step 1: Handle base cases - empty list or a list with just one node is a palindrome.

 Step 2: Find the middle of the linked list using slow and fast pointer technique.
 Step 3: Reverse the second half of the linked list.
 Step 4: Compare the first half of the original list with the reversed second half.
 Step 5: If all values match, the list is a palindrome; otherwise, it's not.
 Step 6: Optionally, restore the original list structure by reversing the second half again.
 Step 7: Return the result - true if palindrome, false otherwise.

Submitted Code :