234. Palindrome Linked List
https://leetcode.com/problems/palindrome-linked-list/
Problem
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: falseExample 2:
Input: 1->2->2->1
Output: trueFollow up: Could you do it in O(n) time and O(1) space?
Solution
/**
* 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 *slow = head, *fast = head;
while (fast != nullptr) {
fast = fast->next;
if (fast != nullptr) fast = fast->next;
slow = slow->next;
}
ListNode *tail = reverse(slow);
int i = 0;
while (tail != nullptr) {
if (head->val != tail->val) return false;
head = head->next;
tail = tail->next;
}
return true;
}
ListNode* reverse(ListNode* head) {
if (head == nullptr) return nullptr;
ListNode* new_next = head->next;
head->next = nullptr;
return reverse(head, new_next);
}
ListNode* reverse(ListNode *current, ListNode *next) {
if (next == nullptr) return current;
ListNode* new_next = next->next;
next->next = current;
return reverse(next, new_next);
}
};#linkedlist
Last updated
Was this helpful?