/**
* 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==NULL || head->next==NULL) return true;
ListNode *slow=head;
ListNode *fast=head;
while(fast->next && fast->next->next){ // 找到中位数 : (int) (n+1)/2;
slow=slow->next;
fast=fast->next->next;
}
ListNode *nextPtr=slow->next;
slow->next=NULL;
while(nextPtr){ // 链表的倒置
ListNode *tem=nextPtr->next;
nextPtr->next=slow->next;
slow->next=nextPtr;
nextPtr=tem;
}
ListNode *ptrA=head,*ptrB=slow->next;
while(ptrA && ptrB){// 比较
if(ptrA->val!=ptrB->val) return false;
ptrA=ptrA->next;
ptrB=ptrB->next;
}
return true;
}
};
Palindrome Linked List
最新推荐文章于 2021-03-02 15:23:07 发布