在排序的链表中插入segfault

Insert into sorted linked list segfaults

本文关键字:插入 segfault 链表 排序      更新时间:2023-10-16

在"SortedInsert"中,头总是零,然后代码无论如何都是segfault。。。真的很令人沮丧。知道为什么尽管我把它设置为某个值,但头总是零吗?还有为什么代码通常会出错?感谢

#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;
}

SortedInsert有自己的头指针副本。当您在函数内部更改头时,它不会影响main中的值。解决方案是通过引用或通过传递地址来传递头。

void SortedInsert(Node** head, int value) {
    //Use *head to refer to the head of the list
}
int main() {
    ...
    Node* sortedList = 0;
    SortedInsert(&sortedList, ...);
    ...
}

void SortedInsert(Node*& head, int value) {
    //Use head to refer to the head of the list
}
int main() {
    ...
    Node* sortedList = 0;
    SortedInsert(sortedList, ...);
    ...
}

尝试以下

void SortedInsert( Node* &head, int value )
{
    if ( head == nullptr || value < head->data )
    {
        head = new Node { head, value };
    }
    else
    {
        Node *current = head;
        while ( current->next != nullptr && !( value < current->next->data ) )
        {
            current = current->next;
        }
        Node *tmp = new Node { current->next, value };
        current->next = tmp;
    }
}

至于你的函数实现,那么函数处理的是头的副本。副本的任何更改都不会影响论点本身。您应该通过引用传递头,或者从函数返回头。