看起來像在「SortedInsert」中,頭部始終爲零,然後代碼段錯誤...無論如何...真的令人沮喪。任何想法爲什麼頭總是零,即使我把它設置爲某些東西,然後爲什麼代碼段錯誤一般? 感謝插入已排序的鏈接列表段落默認
#include <iostream>
#include <cassert>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
struct Node {
Node* next = 0;
int data;
~Node(){
if (next != 0){
delete next;
}
}
};
void SortedInsert(Node* head, int value){
if(head == 0){
Node* header = new Node;
header->data = value;
head = header;
return;
}
cout << "TEST" << endl;
Node* temp = head;
while(temp != 0){
if(value > temp->data){
Node* insert = temp->next;
Node* otherTemp = new Node;
otherTemp->data = value;
temp->next= otherTemp;
temp->next->next = insert;
}
temp=temp->next;
}
return;
}
int main() {
srand(32);
Node* sortedList = 0;
for (int i = 0; i < 10; i++){
SortedInsert(sortedList, rand() % 100);
}
Node* temp = sortedList;
for (int i=0; i < 9; i++){
assert(temp->data <= temp->next->data);
temp = temp->next;
}
delete sortedList;
}
您可能會取消引用未初始化的指針。通過您的調試器來找出錯誤的來源。 –