234. Palindrome Linked List
Description of Problem
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
Constraints:
- The number of nodes in the list is in the range
[1, 105]. 0 <= Node.val <= 9
Follow up: Could you do it in O(n) time and O(1) space?
Solution
Tags: LinkedList
Explanation
If you solve [143. Reorder List], it is not difficult to re-use the logic.
Code (C++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
// 1. Find the middle node
while(fast->next != nullptr && fast->next->next != nullptr){
slow = slow->next;
fast = fast->next->next;
}
// 2. Cut and Reverse
ListNode* curr = slow->next;
ListNode* prev = nullptr;
slow->next = nullptr; // Cut
// Reverse
while(curr != nullptr){
ListNode* temp = curr;
curr = temp->next;
temp->next = prev;
prev = temp;
}
// 3. Merge
ListNode* list1 = head; ListNode* list2 = prev;
while(list1 != nullptr && list2 != nullptr){
if (list1->val != list2->val){
return false;
}
list1 = list1->next;
list2 = list2->next;
}
return true;
}
};
Complexity
Time complexity:
- \(T(n)=O(n)\)
- There are only nearly constant number of n iterations
Auxiliary Space:
- \(S(n)=O(1)\)
- Use only constant number of variables