題意
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
Subscribe to see which companies asked this question.
Show Tags
Show Similar Problems
解法
雙指針,翻轉後半段鏈表,和前半段做對比
實現
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* cur = head;
while(cur->next != NULL){
ListNode* next = cur->next;
cur->next = next->next;
next->next = head;
head = next;
}
return head;
}
bool isPalindrome(ListNode* head) {
if(head == NULL || head->next == NULL) return true;
ListNode* fast = head;
ListNode* slow = head;
ListNode* pre = NULL;
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
pre = slow;
slow = slow->next;
}
pre->next = NULL;
if(fast != NULL && fast->next == NULL) slow = slow->next;
ListNode* rhead = reverseList(slow);
ListNode* p = head;
ListNode* q = rhead;
while(q != NULL && p != NULL){
if(p->val != q->val) return false;
p = p->next;
q = q->next;
}
if(q != NULL || p != NULL) return false;
return true;
}
};