c_cpp PalindromeLL,治法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp PalindromeLL,治法相关的知识,希望对你有一定的参考价值。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head){
// Iterative using 3 pointers
if(head==NULL){
return head;
}
ListNode* pre=NULL;
ListNode* cur=head;
ListNode* nex=head->next;
while(nex!=NULL){
ListNode* temp=nex->next;
nex->next=cur;
cur->next=pre;
pre=cur;
cur=nex;
nex=temp;
}
// for the last node
cur->next=pre;
head=cur;
return head;
}
bool isPalindrome(ListNode* head) {
if(head==NULL || head->next==NULL){
return true;
}
int len=0;
ListNode* cur=head;
while(cur!=NULL){
len++;
cur=cur->next;
}
// cout<<"len "<<len<<endl;
int counter;
if(len&1){ // odd
// single mid point
counter=(len/2)+1; // syymetric about mid 7len -> 4mid
}else{
counter=(len/2); // symm along with mid 4len -> 2mid
}
// cout<<"counter "<<counter<<endl;
int i=1;
cur=head;
while(i<counter){
cur=cur->next;
i++;
}
ListNode* mid=cur;
mid->next=reverse(mid->next); // reverse the list to right of mid
ListNode* leftRunner =head;
ListNode *rightRunner=mid->next; // runs starting from right of mid
while(true){
if(leftRunner->val!=rightRunner->val){
return false;
}
if(len&1){
if(leftRunner->next==mid){
return true;
}
}else{
if(leftRunner==mid){
return true;
}
}
leftRunner=leftRunner->next;
rightRunner=rightRunner->next;
}
return false;
}
};
以上是关于c_cpp PalindromeLL,治法的主要内容,如果未能解决你的问题,请参考以下文章