Insert link list in ascending order

Asked 2 years ago, Updated 2 years ago, 131 views

I am studying single linked list with c++ now. I want to insert values in ascending order, but I keep getting errors. Putting 1 and 0 works well, but putting 0 and 1 does not work. Maybe if (p == NULL) This part doesn't work, so I don't know why it's not working. I'd appreciate your help.

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

class List {
private:
    Node* head;
public:
    List() {
        head = 0;
    }
    void insert(int data) {
        Node* temp = new Node;
        temp->data = data;
        temp->next = 0;
        Node* p, * q;
        if (head == 0) {
            head = temp;
        }
        else if (temp->data < head->data) {
            temp->next = head;
            head = temp;
        }
        else {
            p = head;
            q = head;
            while ((p->data <= temp->data) and (p != 0)) {
                q = p;
                p = p->next;
            }
            if (p == 0) {
                p->next = temp;
            }
            else {
                temp->next = p;
                q->next = temp;
            }
        }
    }
    void display() {
        if (head == 0) {
            cout << "list is empty";
        }
        else {
            Node* p;
            p = head;
            while (p != 0) {
                cout << p->data;
                p = p->next;
            }
            cout << endl;
        }
    }
};
int main() {
    List a;
    a.insert(0);
    a.insert(1);
    a.display();
}

linked-list c++

2022-09-21 10:41

1 Answers

I would appreciate it if you could also tell me what kind of error occurred when the error occurred.

The following runtime error appears to be occurring:

signal: segmentation fault (core dumped)

Segmentation faults usually occur when an invalid memory address is accessed.

while ((p > data < - = temp > data) and a (p! = 0)) , p the boards whether or not, seen as an attempt to tour the OK. & & is dealt with from left to right. As a result, p iyeodo boards are - > p data memory address to get access to the wrong ceremony performed. (p! = 0) and (- > p data < - = temp > data) , you need to change.

if (p == 0)
{
    p->next = temp;
}

If you look at this code, you will access next when p is you. Accessing the null pointer results in runtime errors because it is an invalid memory address access.

For your information, and is an operator supported by the C++ standard, but there are some compilers that are unexpectedly not supported. Therefore, it is recommended to use && instead of alternative operators.


2022-09-21 10:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.