bool isPalindrome2(ListNode* head) {
if (head==NULL)
{
return true;
}
ListNode* fast = head;
ListNode* slow = head;
while (fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
}
slow = slow->next;
ListNode*ptr,*p1,*p2;
ptr = slow;
p1 = NULL;
while (ptr)
{
p2 = ptr;
ptr = ptr->next;
p2->next = p1;
p1 = p2;
}
p2 = head;
while (p1 && p2)
{
if (p1->val!=p2->val)
{
return false;
}
p1=p1->next;
p2=p2->next;
}
return true;
}
struct ListNode {
int val;
struct ListNode *next;
};
bool isPalindrome(ListNode* pHead){
if (pHead == NULL || pHead->next==NULL)
{
return true;
}
int count = 0;
ListNode* p = pHead,*q;
while(p)
{
p=p->next;
count++;
}
int i = 0;
p = pHead;
ListNode *nhead = NULL;
while (i < (count/2))
{
if (nhead==NULL)
{
nhead = p;
p = p->next;
nhead->next = NULL;
}
else
{
q = p;
p = p->next;
q->next = nhead;
nhead = q;
}
i++;
}
if (count%2)
{
p=p->next;
}
while (p)
{
if (p->val != nhead->val)
{
return false;
}
p=p->next;
nhead=nhead->next;
}
return true;
}
int main(){
int s[]={1,2,3,2,7};
int i;
ListNode *head = NULL;
ListNode*p,*q;
for (i=0;i<5;i++)
{
p=new ListNode;
p->val=s[i];
p->next=NULL;
if (head==NULL)
{
head=p;
q=p;
}
else{
q->next=p;
q=p;
}
}
if (isPalindrome(head) == true)
{
cout<<"是回文\n";
}
else{
cout<<"不是回文\n";
}
while(1);
}