检查链表是否为回文

checking if a linked list is palindrome or not

本文关键字:回文 是否 链表 检查      更新时间:2023-10-16

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

我在链表中插入了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;
    }
}