【发布时间】:2020-11-13 12:20:51
【问题描述】:
我被困在一个问题上,无法弄清楚为什么我在释放后会出现运行时错误堆使用。我读到过,当我们释放一些内存然后用指针访问它时,可能会出现这个错误,但在我的代码中我我没有释放任何东西,所以为什么会出现这个错误。 让我解释一下,我有一个包含 3 个节点 0->2->1->NULL 的链表。目前,我的第二个指针指向 2,我只想更改链接 1->2。现在,当我分配 pre=NULL,cur=second->next 时,它可以正常工作并成功运行,但是当我执行 pre=second 和 cur=second->next 时,它会给出这个运行时错误。我的意思是我不在乎 2 应该指向NULL 让 2 指向 1,但我希望我的 1 应该指向 2。 这是代码:这会产生运行时错误,而在我的本地编译器中它运行成功。因为这个问题是关于 leetcode 的,而在 leetcode 中我看不到 main 函数。
#include<iostream>
using namespace std;
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:
int length(ListNode* temp)
{
int count=0;
while(temp!=NULL)
{
temp=temp->next;
count++;
}
return count;
}
bool isPalindrome(ListNode* head)
{
bool flag=1;
int len=length(head)/2; //FUNCTION TO RETURN LENGTH OF LINKED LIST
ListNode *first=head,*second=head;
for(int i=1;i<=len;i++)
{
second=second->next;
}
ListNode *pre=second,*cur=second->next;
while(cur!=NULL)
{
ListNode *temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
for(int i=1;i<=len;i++)
{
if(first->val!=pre->val)
{
flag=0;
break;
}
first=first->next;
pre=pre->next;
}
return flag;
}
};
int main()
{
bool ans;
ListNode *head=NULL;
ListNode *temp=new ListNode(0);
head=temp;
temp=new ListNode(2);
head->next=temp;
temp=new ListNode(1);
head->next->next=temp;
Solution obj1;
ans=obj1.isPalindrome(head);
cout<<ans<<endl;
}
这里是正确的代码,仅更改为 pre=NULL,cur=second。顺便说一下,在下一次迭代中 pre 将变为第二个,cur 将变为第二个->next,这与上述提供运行时的解决方案相同。
ListNode *pre=NULL,*cur=second;
while(cur!=NULL)
{
ListNode *temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
【问题讨论】:
-
评论不适用于扩展讨论或调试会话;这个对话是moved to chat。如果您被要求提供更多信息,请不要在 cmets 中回复。相反,只需 edit 你的问题。
标签: c++ pointers linked-list