-1

这是我的代码。
这个概念是通过快速和慢速两个指针来遍历整个链表,一旦慢在中间,将反转链表并与下半部分比较,后者是快速的。

/**
 * 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 *'
slow= reverse(slow);

4

1 回答 1

1

首先,正如您在下面看到的,您的反向函数返回 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)
于 2020-12-17T13:53:34.027 回答