234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
方法1: reverse
思路:
找到链表的(右)中位值,然后将右半部分反转。遍历比较。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head -> next) return true;
ListNode* slow = head, *fast = head, *prev = nullptr;
while (fast && fast -> next) {
prev = slow;
slow = slow -> next;
fast = fast -> next -> next;
}
prev -> next = nullptr;
ListNode* newHead = reverseHelper(slow);
while (head) {
if (head -> val != newHead -> val) return false;
head = head -> next;
newHead = newHead -> next;
}
return true;
}
ListNode* reverseHelper(ListNode* head){
if (!head -> next) return head;
ListNode* newHead = reverseHelper(head -> next);
head -> next -> next = head;
head -> next = nullptr;
return newHead;
}
};