c++ - 单链表被核心转储的 Hackerearth 练习问题的代码
问题描述
#include <iostream>
#include<vector>
#include <stack>
using namespace std;
class Node
{
public:
int data;
Node* next;
};
int main()
{
int n;
cin >> n;
Node* head = new Node;
Node* ptr = new Node;
head = NULL;
// take the input for the linked list;
for (int i = 0; i< n ;i++)
{
int num;
cin >> num;
Node* temp = new Node;
temp->data = num;
temp->next = NULL;
if(head == NULL)
{
head = temp;
//head->next = NULL;
ptr = head;
}
else
{
ptr->next = temp;
ptr = temp;
}
// linked list made
}
Node* head1 = new Node;
head1 = head;
//ptr->data = NULL;
//ptr->next = NULL;
stack <int> stk;
ptr = head1;
while(ptr != NULL)
{
if(head1->data % 2 != 0)
{
head1 = head1->next;
}
else
{
ptr = head1;
while(ptr->data % 2==0 && ptr != NULL)
{
stk.push(ptr->data);
ptr = ptr->next;
}
while(head1 != ptr)
{
int n ;
n = stk.top();
head1->data = n;
head1 = head1->next;
stk.pop();
}
}
//head1 = ptr;
// replace the values again in the linked list
}
// print the linked list
while(head != NULL)
{
cout << head->data << " ";
head = head->next;
}
}
这是一个练习题 - 1 用于 HackerEarth 上的单链表。代码正在正确编译,但遇到运行时错误,我无法弄清楚原因。
例如如果列表是 {24 , 18, 2 , 5 , 7 , 16 , 12 } 返回的列表应该是 {2, 18 , 24 , 5 , 7 , 12 , 16}
链表中偶数编号的部分应反转,使链表的其余部分保持不变。
此外,我对编程非常陌生,并且是第一次学习数据结构和算法,所以这次请原谅任何不好的缩进和愚蠢的错误。我保证会变得更好。
解决方案
将第 62 行更改为 -while(ptr != NULL && ptr->data % 2==0)
你应该先检查ptr != null
条件,如果它是假的,那么ptr->data
由于短路评估将不会被执行。
https://en.wikipedia.org/wiki/Short-circuit_evaluation
虽然这将消除核心转储错误,但您不会获得所需的输出。你的代码也有逻辑错误。
推荐阅读
- android - 如何在 RxJava2/RxKotlin 中正确组合包含点击事件和值的 Observables
- php - 从 MySQL 结果和 PHP 为 D3.js 树创建分层 JSON?
- php - 巨大的 php 文件有多糟糕?
- c - 我可以从 GDataOutputStream 获取或转换到底层 GOutputStream 吗?
- php - 学说2查询构建器不在之间
- architecture - 用于确定服务价格的基于规则的引擎。建议?
- itext - 目前遇到一个HTML大文件转pdf的问题
- java - 如何以管理员权限运行命令?
- c# - API 控制器实现了 2 个具有不同 URI 的 POST 方法,对一个 POST 的调用未正确路由
- c# - SqlCommand.ExecuteReaderAsync 在存储过程中的第一个 SELECT 语句后停止触发 InfoMessage 事件