This is my code. A circular linked list has two functions, one to insert at the beginning and the other to insert at end. When I run it, it works, but there is an error that it doesn't
display the last node, i think because head=p;
not head->next=p;
but if I do head->next=p;
it is a segmentation error
How can I fix this fault?
#include <iostream>
using namespace std;
struct node {
int info;
node* next;
};
node* head = NULL;
void insert_b(int data) {
node* p = new node; //create
p->info = data; //fill
if (head == NULL) {
head=p;
p->next = head;
}
else {
p->next = head->next;
head->next = p;
}
void traverse() {
node* curr = NULL;
for (curr = head->next; curr != head; curr = curr->next) {
cout << curr->info << " ";
}
}
int main() {
int data;
cout << "enter data: ";
cin >> data;
insert_b(7);
insert_b(2);
insert_b(1);
traverse();
return 0;
}