【发布时间】:2017-01-24 12:37:36
【问题描述】:
我正在尝试用 C++ 中的链接列表实现插入排序。但是,每当我试图将指向新节点的指针分配给链接时,它都会给出“分段错误(核心转储)”。我检查了“(*head)->next = newNode;”这行给出了这个错误。
要运行程序,请编译程序并作为输入复制insertionSort 开始之前的两行注释。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Node
{
public:
int num;
Node *prev;
Node *next;
Node(int input);
};
Node::Node(int input)
{
num = input;
prev = NULL;
next = NULL;
}
/*
5 2
1 5 3 4 2
*/
void insertionSort(Node **head, int newInput)
{
Node* newNode = new Node(newInput);
if (*head == NULL)
{
*head = newNode;
}
else
{
Node *itr = *head;
if (itr->num >= newInput)
{
newNode->next = itr->next;
itr->prev = newNode;
*head = itr;
}
else
{
Node *itr = (*head)->next;
while (itr != NULL)
{
if (itr->num >= newInput)
{
newNode->prev = itr->prev;
newNode->next = itr;
itr->prev = newNode;
newNode->prev->next = newNode;
newNode = NULL;
}
itr = itr->next;
}
if (newNode != NULL)
{
if (itr == NULL) {
(*head)->next = newNode;
}
else
itr->next = newNode;
}
}
}
}
void printList(Node *head)
{
Node *itr = head;
while (itr != NULL)
{
cout << itr->num << " ";
itr = itr->next;
}
cout << endl;
}
int main()
{
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, k;
cin >> n >> k;
Node *head = NULL;
int num, i = -1;
while (++i < n)
{
cin >> num;
insertionSort(&head, num);
}
printList(head);
return 0;
}
【问题讨论】:
-
您是否尝试使用调试器单步执行代码,同时观察变量的值?
-
请删除输入并使用可重现问题的硬编码值。不要依赖别人来猜测你在事情发生时做了什么。
标签: c++ linked-list segmentation-fault