单链表判断是否回文

将链表后半部分反转,判断与前半部分是否相同,再恢复链表
判断回文的普通方法:

  • 分别从开头和结尾往中间遍历
  • 分别从中间往开头和结尾遍历
  • 利用栈,入栈再出栈进行对比
#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;
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值