Palindrome Linked List
Description
- Given the
headof a singly linked list, returntrueif it is a palindrome orfalseotherwise.
Constraints
- The number of nodes in the list is in the range
[1, 10^5]. 0 <= Node.val <= 9
Test Cases
-
Input:
head = [1,2,2,1]
Output:true -
Input:
[1, 2]
Output:false
Code
Approach 1: Using an Array or a Vector
Explanation
- Traverse the linked list and store the values in an array or a vector.
- Use two pointers, one at the start and the other at the end of the array.
- If the values at the two pointers are not equal, return false.
- If the loop completes, return true.
Analysis
- Time Complexity:
O(n) - Space Complexity:
O(n)
Approach 2: Using fast and slow pointers
Explanation
- Use two pointers, one slow and one fast.
- Traverse the linked list using the fast pointer, and move the slow pointer to the middle of the linked list.
- Reverse the second half of the linked list.
- Traverse the first half and the reversed second half of the linked list and check if the values are equal.
- If the loop completes, return true.
Analysis
- Time Complexity:
O(n) - Space Complexity:
O(1)