Linked lists · Exercise 23 of 100
Check for a palindrome
A list is a palindrome when its values read the same forward and backward. For a list of known length, push the first half of its values onto a stack and skip the middle node if the length is odd. Popping one value for each remaining node compares the two halves from the center outward.
Try it yourself
A list contains 9, 4, 1, 4, 9 in that order. Is it a palindrome? Answer yes or no.
One-step hint
Put a finger at each end of the list. Compare the values, then move both fingers inward until they meet or a pair differs.
Worked solution
- Push 9 and then 4 onto the stack. Skip the middle value 1 because it pairs with itself.
- Pop 4 to match the next 4, then pop 9 to match the final 9. Both pairs match, so the answer is yes.