Leetcode 234. Palindrome Linked List
You are given the head of a singly linked list. Return true
if it is a palindrome or false
otherwise.
Input: head = [1,2,2,1]
Output: true
Input: head = [1,2]
Output: false
[1, 10^5]
.0 <= Node.val <= 9
true
./**
* 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) {
if (head == nullptr || head->next == nullptr) {
return true;
}
// Step 1: Find the middle of the linked list
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
// Step 2: Reverse the second half
ListNode* prev = nullptr;
ListNode* curr = slow;
while (curr != nullptr) {
ListNode* next_temp = curr->next;
curr->next = prev;
prev = curr;
curr = next_temp;
}
// Step 3: Compare the first and second half nodes
ListNode* first_half = head;
ListNode* second_half = prev;
while (second_half != nullptr) {
if (first_half->val != second_half->val) {
return false;
}
first_half = first_half->next;
second_half = second_half->next;
}
// Optional Step: Restore the list if necessary
// reverseList(slow);
return true;
}
// Optional: Function to restore the list (if required)
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
while (curr != nullptr) {
ListNode* next_temp = curr->next;
curr->next = prev;
prev = curr;
curr = next_temp;
}
return prev;
}
};
Overall Time Complexity: O(n)
The algorithm uses a constant amount of extra space (excluding the input space for the linked list).
Overall Space Complexity: O(1)
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?