Link list segmentation fault
Oct 2, 2011 at 1:23am UTC
I'm writing a simple link list program, but got stuck. The first insert is working fine, the second one is giving a segmentation fault. Help me figure out the error. Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include<iostream>
using namespace std;
struct node{
int data;
node *next;
};
void insert(int num, node *&p);
void addAsFirst(int num, node *p);
int deleteNode(int num, int pos, node *p);
void print(node *&p);
int main(){
node *p;
p = NULL;
insert(5, p);
insert(8, p);
insert(6, p);
print(p);
return 0;
}
void insert(int n, node *&p){
node *q, *r;
if (p==NULL){
p = new node;
p->data = n;
p->next = NULL;
cout<<"p: " <<p->data<<endl;
}
else {
q = p;
while (!q->next){
cout<<"q: " <<q->data<<endl;
q = q->next;
}
r = new node;
r->data = n;
r->next = NULL;
q->next = r;
}
}
void print(node *&p){
node *q;
if (p == NULL){
cout<<"Link list is empty\n" ;
}
else {
q = p;
while (q != NULL){
cout<<q->data<<" \t" ;
q = q->next;
}
}
}
Topic archived. No new replies allowed.