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();
}
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.
611 GDB gets version error when attempting to debug with the Presense SDK (IDE)
914 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
572 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
617 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.