编辑:我刚试着做while (temp != NULL && newNode->info > temp->info){,但由于某些原因还是不能工作,我试着输入5和4,但再次遇到分割错误
对于糟糕的代码,我很抱歉,我是个新手,我正在尝试创建一个排序的单链表。我不知道它有什么问题,如果有人能帮我解决这个问题,我会非常感激的。
我也许能够输入一些值,每次出于某种原因(不是因为我输入了-1),每次都有不同数量的值。然后它只会显示“发生了异常。分割错误。”在这一行,我不确定为什么,因为我比较的是值,而不是内存地址:
while (newNode->info > temp->info){
完整代码:
#include <iostream>
using namespace std;
class node {
public:
int info;
node *next;
node (int data, node *ptr = 0) {
info = data;
next = ptr;
}
};
class osll{
public:
node *head, *tail;
osll(){
head = tail = 0;
}
bool isEmpty(){
return head == 0;
}
void sort(int input){
node *newNode = new node (input);
if (isEmpty()){
newNode ->next = head;
head = newNode;
if (tail == 0)
tail = head;
}
if (newNode ->info > head ->info){
node *temp = head;
while (newNode->info > temp->info){
temp = temp ->next;
}
// will figure out how to link newNode to
// whatever temp value that stops here
// once this error goes away
}
}
};
int main () {
osll l;
int input = 0;
while (input != -1) {
cout << "Enter a value: ";
cin >> input;
l.sort(input);
}
return 0;
}发布于 2021-09-03 21:31:21
如果您的新数字是列表中的最大值,则会导致分段错误,因为您不会在while循环中检查是否到达了列表的末尾。在最后一个元素temp将为空之后,所以.temp->info将导致分段错误。
例如,您应该这样做(第40行)
while (temp != null && newNode->info > temp->info)https://stackoverflow.com/questions/69050477
复制相似问题