1,找到中间节点然后反转后半部,
2,从头到尾依次比较每个节点的值
当链表个数是偶数个数的时候很好理解,当时奇数的时候有一个比较tricky的地方
1->2->3->NULL
反转后半部之后为3->2->NULL.
前半部1->还是指向2 1->2->NULL.
因此可以同等长度的比较,知道后半部的指针为空
half = reverseList(slow);
while(half){
if(half->val == head->val){
half = half->next;
head = head->next;
}else
return false;
}
struct ListNode* reverseList(struct ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
struct ListNode *node;
node = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return node;
}
bool isPalindrome(struct ListNode* head) {
struct ListNode *slow, *fast;
slow = fast = head;
struct ListNode *half;
while(fast){
fast = fast->next;
if(fast){
fast = fast->next;
slow = slow->next;
}
}
//slow is midst
half = reverseList(slow);
while(half){
if(half->val == head->val){
half = half->next;
head = head->next;
}else
return false;
}
return true;
}
网友评论