c++ - 检查链表是否是回文

标签 c++ list palindrome

我正在编写一个程序来检查单链表是否是回文。我正在使用通过迭代进行反转的概念。

我在链表中​​插入了2,3,5,3,2,并反转了它,基于这样的想法:如果反转后得到的链表与反转前相同,那么它是回文。但我无法用 match 语句结束程序。我怎样才能匹配这两个列表?

这是我的代码:

struct Node{
    int data;
    Node* next;
};
Node*head;

void Insert(int x)
{
    Node*temp=new Node();
    temp->data=x;
    temp->next=head;
    head=temp;  
}

void print()
{
    Node*temp=head;
    cout<<"list is";
    while(temp!=NULL) 
    {
        cout<<temp->data;
        temp=temp->next;
    }
}

void rec()
{
    Node*current, *prev, *next;
    current=head;
    prev=NULL;
    while(current!=NULL)
    {
        next= current->next;
        current->next= prev;
        prev= current;
        current=next;
    } 
    head=prev;
}

int main()
{
    clrscr();
    Node*head=NULL;
    Insert(2);
    Insert(3);
    Insert(5);
    Insert(3);
    Insert(2);
    cout<<"list before reversing is\n";
    print();

    cout<<"\n";
    cout<<"list after reversing is \n";
    rec();
    print();

    getch();
}

最佳答案

不是单独的逆向函数,而是有一个用于检查回文是否回文的函数。在该函数中,反转列表并存储在临时列表中。 然后迭代比较各个节点->数据。如果全部匹配,则为回文,否则跳出循环并设置为 false。

关于c++ - 检查链表是否是回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30619686/

相关文章:

c++ - ofstream-保存一个函数返回一个txt

c++ - 编译没有ros的roscpp(使用g++)

python - 如何从长度可变的元组列表中提取数据

list - 在 Erlang ETS 中存储列表

c - 两个 3 位数字的乘积是回文数

c++ - Boost 并发库在使用 GNU C++/LLVM C++ 编译时表现不同

C++双数据类型问题

java - 我应该将 ArrayList 声明/初始化为列表、ArrayList 还是 <Cat> 的 ArrayList

C++ 递归和指针问题

c - 如何处理错误 "control may reach end of non void function"?