简体   繁体   English

插入已排序的链表段错误

[英]Insert into sorted linked list segfaults

It looks like in "SortedInsert", the head is always zero and then the code segfaults anyway... really frustrating.它看起来像在“SortedInsert”中,头部总是零,然后代码段错误无论如何......真的很令人沮丧。 Any idea why the head is always zero even though I set it to something, and then why the code segfaults in general?知道为什么即使我将其设置为某些内容,头部也始终为零,然后为什么代码通常会出现段错误? Thanks谢谢

#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 has its own copy of the head pointer. SortedInsert有它自己的头指针副本。 When you change head inside the function it doesn't affect the value in main.当您在函数内部更改 head 时,它不会影响 main 中的值。 The solution is to pass head by reference or by passing the address.解决方法是通过引用或通过地址传递head。

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

Or或者

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

Try the following尝试以下

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

As for your funcion implementation then the function deals with a copy of the head.至于您的功能实现,则该功能处理头部的副本。 Any changes of the copy do not influence on the argument itself.副本的任何更改都不会影响参数本身。 You should pass the head by reference or return the head from the function.您应该通过引用传递头部或从函数返回头部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM