检查链表是否为回文
checking if a linked list is palindrome or not
我正在写一个程序来检查一个单链表是否是一个回文。我正在使用通过迭代反转的概念。
我在链表中插入了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 isn";
print();
cout<<"n";
cout<<"list after reversing is n";
rec();
print();
getch();
}
代替单独的函数来反转,有一个函数来检查是否回文。在该函数中,将列表反转并存储在临时列表中。然后迭代并比较每个节点->数据。如果全部匹配,则为回文,否则跳出循环并设置false。
创建一个双链表(添加Node * prev)到列表的节点。然后,这是一个迭代和比较两个迭代器的问题,像这样:
bool isPalindrome(Node * head, Node * tail)
{
Node * inc = head, * dec = tail;
while (inc != nullptr && dec != nullptr)
{
if (inc->data != dec->data) return false;
inc = inc->next;
dec = dec->prev;
}
return inc == nullptr && dec == nullptr;
}
始终尝试为任务使用最佳容器
使其递归,并在返回时检查
#include <functional>
using namespace std;
struct Node
{
int data;
Node* next;
};
bool isPalin( Node* h )
{
function<bool(Node*)> ip_rec = [&](Node* p) -> bool
{
if(p)
{
if( ! ip_rec(p->next) ) return false;
if( p->data != h->data ) return false;
h=h->next;
}
return true;
};
return ip_rec(h);
}
我的解决方案在c++ .....很容易,但不确定代码是否优化了一个…
bool isPalindrome(Node *head)
{
int count=0;
Node *ptr, *nptr;
ptr=head;
while(ptr!=NULL)
{
count++;
ptr=ptr->next;
}
ptr=head;
int arr[count],count1=0;
while(ptr!=NULL)
{
// cout<<ptr->data;
arr[count1]=ptr->data;
count1++;
ptr=ptr->next;
}
ptr=head;
while(ptr!=NULL)
{
if(ptr->data!=arr[count-1])
return false;
ptr=ptr->next;
count--;
if(count==-1)
return true;
}
}
相关文章:
- 如何检查C ++ STL列表是否为回文?
- C++ - 检查结构数据类型中的单词是否为回文
- 确定用户输入是否为带C++的回文
- 是否可以检查存储在堆栈上的单词是否是回文,而C++中没有任何附加数据结构
- 任何人都可以检查这个回文 c++ 代码是否正确
- 寻找一种更有效的方法来使用 STL 函数检查字符串是否为回文
- 我试图编写一个代码来查找一个单词是否是回文,但它不起作用。怎么了?
- 如何在不使用数学的情况下知道一个数字是否是回文
- 内联程序集 - 检查单词是否为回文
- 检查子数组是否为带指针的回文数组
- 验证字符串是否为回文的函数
- 验证代码以检查数字是否为回文
- 检查数字是否是C++中的回文
- 需要修改堆栈/链表程序以确定单词是否为回文
- 检查数字是否为回文
- 看看我们是否可以获得回文
- 使用不同的函数(C++)测试一个数字是否是回文
- 检查字符串是否为回文
- 目的:检查用户输入的字符串,以确定它是否为回文
- C++-使用堆栈来确定C样式字符串是否为回文