Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 回文链表_C++_Linked List_Palindrome - Fatal编程技术网

C++ 回文链表

C++ 回文链表,c++,linked-list,palindrome,C++,Linked List,Palindrome,这是我的代码。 其概念是通过快速和慢速两个指针遍历整个linkedlist,一旦慢速位于中间,将反转列表并将其与快速的下半部分进行比较 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), ne

这是我的代码。
其概念是通过快速和慢速两个指针遍历整个linkedlist,一旦慢速位于中间,将反转列表并将其与快速的下半部分进行比较

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode *fast= head;
        ListNode *slow= head;
        
        while( fast!=NULL&&fast->next !=NULL)
            {
            fast=head->next->next;
            slow=head->next;
        }
        slow= reverse(slow);
        fast= head;
      
        while(slow!=NULL)
            { 
               if(fast->data!=slow->data)
                   return false
                   slow =slow->next;
            fast=fast->next;
            }
        return true;
    }
    public: ListNode reverse(ListNode *head){
       ListNode *prev = NULL;
        while(head!=NULL)
            {
            ListNode* nextnode=head->next;
            head->next=prev;
            prev=head;
            head=nextnode;
            
        }
        return prev;
    
    }
};
我得到这个小错误,请帮助纠正代码

第22行:字符15:错误:从“不兼容”分配到“ListNode*” 键入“ListNode”
慢=反向(慢)


首先,正如您在下面看到的,您的反向函数返回ListNode类型的对象

ListNode reverse(ListNode* head)
{
    ListNode* prev = NULL;
    while (head != NULL) {
        ListNode* nextnode = head->next;
        head->next = prev;
        prev = head;
        head = nextnode;
    }
    return prev;
}
但是,您愿意返回类型为ListNode*的“prev”,因此我建议您在反向函数中将返回类型从“ListNode”更改为“ListNode*”,如下所示:

ListNode* reverse(ListNode* head)
您应该(或将)收到一个类似的错误
return prev在<代码>的末尾反向<代码>;这有助于确定问题所在吗?“未修复”是一个几乎毫无价值的评论。你改变了什么?结果如何?