将链表后半部分反转,判断与前半部分是否相同,再恢复链表
判断回文的普通方法:
- 分别从开头和结尾往中间遍历
- 分别从中间往开头和结尾遍历
- 利用栈,入栈再出栈进行对比
#include <iostream>
using namespace std;
struct Node{
int value;
Node *next;
};
void createList(Node* tail,int n){
cin>>tail->value;
tail->next=NULL;
n--;
for(int i=0;i<n;i++){
Node *p=new Node;
cin>>p->value;
tail->next=p;
p->next=NULL;
tail=p;
}
}
void showList(Node *head){
Node *p=head;
while(p){
cout<<p->value<<" ";
p=p->next;
}
cout<<endl;
}
Node *reverseList(Node *head){
Node *p1,*p2,*p3;
p1=head;
p2=p1->next;
while(p2){
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
head->next=NULL;
head=p1;
return head;
}
Node *reverseList2(Node *head){
Node *p,*q;
p=head->next;
while(p->next!=NULL){
q=p->next;
p->next=q->next;
q->next=head->next;
head->next=q;
}
p->next=head;
head=p->next->next;
p->next->next=NULL;
return head;
}
bool isPalindrome(Node *head){
bool flag=true;
Node *p1=head,*p2=head;
//找到中间节点
while(p2->next!=NULL&&p2->next->next!=NULL){
p1=p1->next;
p2=p2->next->next;
}
//p1是中间节点,p2是后半部分的开头
p2=p1->next;
//中间节点后接NULL,防止死循环
p1->next=NULL;
//后半部分反转
Node *p3=reverseList(p2);
Node *p4=p3;
Node *pHead=head;
//判断是否回文
while(pHead->next!=NULL&&p3->next!=NULL){
if(pHead->value!=p3->value){
//cout<<pHead->value<<"-"<<p3->value<<endl;
flag=false;
}
pHead=pHead->next;
p3=p3->next;
}
//后半部分再反转回来
Node *q=reverseList(p4);
//从中间节点接上
p1->next=q;
return flag;
}
int main() {
Node *head=new Node;
createList(head,5);
showList(head);
if(isPalindrome(head)){
cout<<"true"<<endl;
}else{
cout<<"false"<<endl;
}
showList(head);
return 0;
}