在链表回文中得到错误答案 我编写了C++代码,检查链接列表是否为回文。代码如下所示

在链表回文中得到错误答案 我编写了C++代码,检查链接列表是否为回文。代码如下所示,c++,stack,C++,Stack,每次运行程序时,我都会得到返回为1的值。在给定的示例中,我使用了非回文字符串,然后我得到了与回文字符串相同的答案 我使用C++标准模板库执行这个代码 #include<iostream> #include<stack> using namespace std; struct node{ char data; node *next; }; void push(struct node** head

每次运行程序时,我都会得到返回为1的值。在给定的示例中,我使用了非回文字符串,然后我得到了与回文字符串相同的答案

我使用C++标准模板库执行这个代码

#include<iostream>
    #include<stack>
    using namespace std;

    struct node{
        char data;
        node *next;
    };



    void push(struct node** head,char data)
    {
        struct node *newnode= new node;
        newnode->data=data;
        newnode->next=(*head);
        (*head)=newnode;
    }

    void print(struct node *ptr)
    {
        while(ptr!=NULL)
        {
            cout<<"  " <<ptr->data;
            ptr=ptr->next;
        }
    }

    //this is the function to check palindrome
    int checkpalindrome(node *head)
    {
        stack<char>s;
        node *current=head;
        while(current!=NULL)
        {
            s.push(current->data);
            current=current->next;  
        }


        while(current!=NULL && !s.empty() )
        {
                int ele=s.top();
                s.pop();
                if(ele==current->data)
                current=current->next;
                else
                {
                    return 0;
                    break;
                }

        }
    }


    int main(){

    node *first=NULL;
        push(&first,'a');
        push(&first,'b');
        push(&first,'b');
        push(&first,'d');
        int c=checkpalindrome(first);
        if(c==0){cout<<"not a palindrome";
        }
        else
        {cout<<"its a palindrome";
        }

    }
#包括
#包括
使用名称空间std;
结构节点{
字符数据;
节点*下一步;
};
无效推送(结构节点**头,字符数据)
{
结构节点*newnode=新节点;
新建节点->数据=数据;
新建节点->下一步=(*头);
(*头)=新节点;
}
作废打印(结构节点*ptr)
{
while(ptr!=NULL)
{
coutnext;
}
while(current!=NULL&&!s.empty())
{
int ele=s.top();
s、 pop();
如果(元素==当前->数据)
当前=当前->下一步;
其他的
{
返回0;
打破
}
}
}
int main(){
node*first=NULL;
推送(&首先,“a”);
推送(&第一个,'b');
推送(&第一个,'b');
推送(&first,'d');
int c=检查回文(第一);

如果(c==0){cout您需要重置
current
以指向头部,则第二个while循环不会在回文函数中执行,因为它在该点为NULL

// ...

*current = head; // RESET current

while(current!=NULL && !s.empty())
{
    // ...
}

// ...

朋友,我想你已经找到了解决方案,但作为编程经验,我想添加的东西很少。你的代码创建了链表,但当你尝试跟踪元素时,链表以与存储相反的顺序存储元素,它实际上就像堆栈一样。如果你先打印指针,它将打印dbba,而你存储addb。还有检查回文ome函数如果它是回文的,你就没有把返回值放进去,这是错误的做法。如果它满足条件,我建议你加上返回值,说值1。这在你的列表是回文的时候是一致的。最后,在同一个函数中,随机观察:为什么你
#包括
,而不是用它来实现你的目标own?(完全是修辞性的)@assimilator也许他打算用它,但改变了主意,我不知道”_(ツ)_/'@assimilator我也将尝试自己的实现