0

I'm trying to create one way node where inserted values are sorted. I tried do this like this, but i receive error on debuging. Please about help, its 's very important for me.

struct list {
int key;
list* next;
};

void add(list *&head, int key) {

list* tmp = new list;
tmp->key = key;

list* current = head;

if (current == NULL) {
    tmp->next = head;
    head = tmp;
    return;
}

while (current != NULL) {


    if (current->key == key) {
        cout << "Taki klucz juz istnieje" << endl;
        return;
    }
    cout << current->next << endl;

    if (key > current->key && current->next == NULL)  {
        cout << "---------" << endl;
            current->next = tmp;
            return;
    }
    if (key > current->key && current->next!=NULL && key < current->next->key) {
        list* currentNextCopy = current->next;
        current->next = tmp;
        tmp->next = currentNextCopy;
        return;
    }

    current = current->next;
}
    tmp->next = head;
    head = tmp;
}

int main()
{
srand(time(NULL));
list* head = NULL;
add(head, 2);
add(head, 4);
add(head, 3);
add(head, 1);
add(head, 5);

}

Maybe problem is very stupid, but I'm beginner at C++. Very please help.

robert
  • 41
  • 6
  • 0xCD... is a sentinel value for uninitialized heap memory. https://stackoverflow.com/a/127404/920069 You might consider a constructor for your list nodes to initialize the `next` pointer to NULL. You can step through the code in the debugger to see where it goes wrong. – Retired Ninja Nov 01 '20 at 20:30
  • in the `key > current->key` case `tmp->next` doesn't get initialised – Alan Birtles Nov 01 '20 at 20:33

0 Answers0