我正在编写一个程序来检查单链表是否是回文。我正在使用通过迭代进行反转的概念。
我在链表中插入了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/