You are passing a NULL value node *x=NULL; to the insert() function. Then in your insert() function, you attempt to access "next" from the NULL pointer? That's the problem. They are all NULL.
Do you have to pass in a node pointer to the insert() function? Is that one of your requirement for implementation?
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
Nope, you should check if x is NULL first instead. If it is NULL, create a new node to x and set next to itself; otherwise, pass in the x and the data as in your original code. Hmm... You need a setNext() function here...
node *x=NULL;
int a;
for(int i=0;i<5;i++){
cin>>a;
if (x==NULL) {
x = new node(a, NULL);
x.setNext(x); // to make it circular (need to implement setNext()
}
else {
insert(x,a);
}
}
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
No, it is not normal. It seems that your print() function is not working correctly.
In a circular linked list, there shouldn't be NULL for "next" because the ending is always pointing to the head. In your print(), you could actually implement a while loop in there instead of having print2().
void print (node *h) {
if (h!=NULL) { // print out if the list is not empty
cout << h->data << " ";
node *current = h->next;
while (current!=h) { // exit if it comes back to head
... // display & move to the next node
}
}
else {
// display the message that the list is empty
}
}
Taywin
Posting Maven
2,633 posts since Apr 2010
Reputation Points: 275
Solved Threads: 375
Skill Endorsements: 17
Or simply call print2(h, h); from print(), so that you don't skip the first node....
raptr_dflo
Practically a Master Poster
605 posts since Aug 2010
Reputation Points: 76
Solved Threads: 83
Skill Endorsements: 1
Please mark your thread as "solved" when you're finished with it. Thanks!
raptr_dflo
Practically a Master Poster
605 posts since Aug 2010
Reputation Points: 76
Solved Threads: 83
Skill Endorsements: 1
Question Answered as of 1 Year Ago by
Taywin,
raptr_dflo
and
Tumlee