c++ 类型“struct ListNode”的空指针内的成员访问(解决方案.cpp)|未定义行为消毒剂

lrl1mhuk  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(86)
  • 我正在练习一个基于单链表的问题,这个问题似乎很简单。问题是,如果给定的单链表是回文,则返回true,否则返回false。* 我首先通过遍历到最后一个节点来获得列表的长度,然后将列表的所有值推送到一个向量,然后检查如果从最后一个节点开始遍历,该向量是否相同,如果相同,则返回true或false。

但我得到了这个错误说:
第24行:字符24:运行时错误:类型“struct ListNode”的空指针内的成员访问(解决方案.cpp)总结:未定义行为消毒剂:未定义行为prog_joined。cpp:33:24

class Solution {
    public:
    bool isPalindrome(ListNode* head) {
        struct ListNode *temp;
        int j,data,l=0,r;
        vector <int> v;
        temp=head;
        while(temp!=NULL){//to get length of the linked list
            j++;
            temp=temp->next;
        }
        temp=head;
        for(int i=0;i<j;++i){
            data=temp->val;
            v.push_back(data);
            temp=temp->next;
        }
        r=v.size()-1;
        while (l<=r){
            if(v[l]!=v[r]) return false;
        }
        return true;
    }
        
        
};
fhg3lkii

fhg3lkii1#

这是你的问题的另一种解决方案。试试这个然后告诉我

class Solution {
public:
bool isPalindrome(ListNode* head) {
    if (!head || !head->next) {
        return true; // empty list or single node list is a palindrome
    }
    // Find the middle of the linked list using slow and fast pointers
    ListNode *slow = head, *fast = head;
    while (fast->next && fast->next->next) {
        slow = slow->next;
        fast = fast->next->next;
    }
    // Reverse the second half of the linked list
    ListNode *prev = nullptr, *curr = slow->next;
    while (curr) {
        ListNode *next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    // Check if the first and second half of the linked list are identical
    ListNode *p1 = head, *p2 = prev;
    while (p2) {
        if (p1->val != p2->val) {
            return false;
        }
        p1 = p1->next;
        p2 = p2->next;
    }
    // Reconstruct the linked list by reversing the second half back
    // to its original order before returning
    curr = prev;
    prev = nullptr;
    while (curr) {
        ListNode *next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    slow->next = prev;
    return true;
}

};

相关问题