C++ 我的代码中出现了分段错误(SIGSEGV)
给定一个大小为N的整数单链表。任务是检查给定的链接列表是否为回文 输入: 输入的第一行包含测试用例的数量T。对于每个测试用例,输入的第一行包含链表N的长度,下一行包含N个整数作为链表的数据 输出: 如果链表是回文列表,则每个测试用例的输出将为1,否则为0 用户任务: 任务是完成函数isAlindrome,该函数将head作为唯一的参数引用,并在链表是否回文时分别返回true或falseC++ 我的代码中出现了分段错误(SIGSEGV),c++,data-structures,C++,Data Structures,给定一个大小为N的整数单链表。任务是检查给定的链接列表是否为回文 输入: 输入的第一行包含测试用例的数量T。对于每个测试用例,输入的第一行包含链表N的长度,下一行包含N个整数作为链表的数据 输出: 如果链表是回文列表,则每个测试用例的输出将为1,否则为0 用户任务: 任务是完成函数isAlindrome,该函数将head作为唯一的参数引用,并在链表是否回文时分别返回true或false Constraints: 1 <= T <= 103 1 <= N <= 50 说明
Constraints:
1 <= T <= 103
1 <= N <= 50
说明:
测试用例1:12,链表是回文的
我的代码:
我得到了分段错误SIGSEGV。考虑一下,len=1的代码是怎么回事: m等于0/2-1,也就是-1。这意味着whilem-&&front将耗尽整个列表。因此,s现在的大小为1,前端指向NULL。现在您可以尝试:
front=front->next;
这会导致segfault,因为front为空
尝试将m-conditions更改为m->0。您调试过它吗?当您的程序崩溃时,您应该进行调试以找出哪里出了问题。通常,您需要一个称为调试器的工具来帮助完成此任务。如果您还没有这样做,那么您还没有准备好向Stack Overflow寻求自愿帮助。有些事情不符合要求。如果你调试了这个问题,你肯定知道的比我得到的更多。您将知道程序的哪个部分导致了内存故障,以何种方式,以及[在某种程度上]原因。我们不能也不会为您远程完成这部分工作。我建议您使用本地开发工具,而不是在线工具。请参阅。调试您自己的代码是编程中的一项基本技能,您需要能够自己完成。这很容易通过调试器发现。应该使用哪种OP。非常感谢。但这给出了一个错误的输出。那么,可能您现在又出现了另一个bug。又到调试器的时候了……你可能在某个地方出了一个错误。可能m->=0?谢谢大家。我能够成功提交我的代码!
Output:
1
0
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stack>
using namespace std;
/* Link list Node */
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
void append(struct Node** head_ref, struct Node **tail_ref, int new_data)
{
struct Node* new_node = new Node(new_data);
if (*head_ref == NULL)
*head_ref = new_node;
else
(*tail_ref)->next = new_node;
*tail_ref = new_node;
}
bool isPalindrome(Node *head);
/* Driver program to test above function*/
int main()
{
int T,i,n,l;
cin>>T;
while(T--){
struct Node *head = NULL, *tail = NULL;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>l;
append(&head, &tail, l);
}
cout<<isPalindrome(head)<<endl;
}
return 0;
}
}
/*This is a function problem.You only need to complete the function given below*/
/*
struct Node {
int data;
struct Node *next;
Node(int x) {
data = x;
next = NULL;
}
};
*/
/*You are required to complete this method */
bool isPalindrome(Node *head)
{
Node *front=head;
if(head==NULL)
{
return -1;
}
int len=0;
while(front!=NULL)
{
front=front->next;
len++;
}
front=head;
stack <int> s;
if(!(len%2))
{
int m=(len/2);
while(m-- && front)
{
s.push(front->data);
front=front->next;
}
int k=(len/2);
while(k-- && !s.empty())
{
int q= s.top();
s.pop();
if(q==front->data)
{
front=front->next;
continue;
}
else
{
break;
}
}
}
else
{
int m=(len/2)-1;
while(m-- && front)
{
s.push(front->data);
front=front->next;
}
front=front->next;
int k=(len/2)-1;
while(k-- && !s.empty())
{
int q= s.top();
s.pop();
if(q==front->data)
{
front=front->next;
continue;
}
else
{
break;
}
}
}
if(s.empty())
{
return 1;
}
else
{
return 0;
}
}
int m=(len/2)-1;
while(m-- && front)
{
s.push(front->data);
front=front->next;
}
front=front->next;