/**
* 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 *p1 = head, *p2 = head;
while (p2->next && p2->next->next) {
p1 = p1->next;
p2 = p2->next->next;
}
// the second part's head
ListNode *secondHead = p1->next;
// reverse the first part
ListNode *firstHead = NULL;
bool evenNodes = p2->next != NULL;
p2 = head;
while (p2 != p1) {
ListNode *next = p2->next;
p2->next = firstHead;
firstHead = p2;
p2 = next;
}
if (evenNodes) {
p1->next = firstHead;
firstHead = p1;
}
while (firstHead && secondHead) {
if (firstHead->val != secondHead->val) {
return false;
}
firstHead = firstHead->next;
secondHead = secondHead->next;
}
return !firstHead && !secondHead;
}
};
234. Palindrome Linked List
最新推荐文章于 2019-02-26 17:06:35 发布