/**
* 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) {
int len = lengthList(head);
if(len < 2) return true;
ListNode *newNode = head;
for(int i = 0; i < (len + 1) / 2; i++) newNode = newNode->next;
return isPalindrome(newNode,head).first;
}
pair<bool,ListNode*> isPalindrome(ListNode *newNode,ListNode *head) {
bool ans = true;
pair<bool,ListNode*> Pair;
if(newNode->next != NULL) {
Pair = isPalindrome(newNode->next,head);
ans = Pair.first; head = Pair.second;
}
if(newNode->val != head->val) ans = false;
head = head->next;
return make_pair(ans,head);
}
int lengthList(ListNode *head) {
int num = 0;
while(head != NULL) {
num++;
head = head->next;
}
return num;
}
};
234. Palindrome Linked List
最新推荐文章于 2017-08-22 08:51:12 发布