类型 'struct ListNode' 的空指针内的成员访问(解决方案.cpp) |未定义的行为清理器



我在练习一个基于单链表的问题,这个问题看起来很简单。问题是,如果给定的单链列表是回文,则返回true,否则返回false我首先通过遍历到最后一个节点来获得列表的长度,然后将列表的所有值推到一个向量上,然后检查向量是否相同,如果从最后一个遍历,如果相同,返回true或返回false。

但我得到了一个错误,说:

第24行:字符24:运行时错误:类型为"structListNode"(solution.cpp(的空指针内的成员访问摘要:UndefinedBehaviorManitizer:未定义的行为prog_joind.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;
}


};

这是您问题的另一种解决方案。试试这个,让我知道:

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;
}
};

相关内容

  • 没有找到相关文章

最新更新