Apr 19, 2011 at 9:10am UTC
Hello,
I'm trying to implement a doubly linked list
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 60 61 62 63
struct node_t
{
int val;
struct node_t *prev,*next;
};
struct node_t *list;
void add(struct node_t *list,int val)
{
if (list==0) // create the first node
{
list=(node_t*)malloc(sizeof (node_t));
list->next=0;
list->prev=0;
list->val=val;
return ;
}
while (list->next!=NULL)
list=list->next;
struct node_t *tmp=new node_t;
tmp->next=0;
tmp->val=val;
tmp->prev=list;
list->next=tmp;
}
void print(struct node_t *list)
{
node_t *p=list;
while (p->prev!=NULL)
p=p->prev;
do
{
cout <<p->val<<" " ;
p=p->next;
}while (p!=0);
}
int main()
{
node_t *list=0;
/* // create the first node
list=new node_t;
list->prev=0;
list->next=0;
list->val=9;
*/
add(list,10);
add(list,20);
add(list,30);
print(list);
}
If I create the first node in main(), then everything is OK but if I try to do the same in add() funcion, then the program crashes. Anyone knows why?
Thnaks for help.
Last edited on Apr 19, 2011 at 9:57am UTC
Apr 19, 2011 at 9:52am UTC
try initilization
node_t * list = NULL
Apr 19, 2011 at 9:57am UTC
You need to pass the list into add()
by reference. Either a reference variable or passing the address of the pointer explicitly (as in C) will do.
add()
malloc
s the first node and new
s the others. This is really bad.
Last edited on Apr 19, 2011 at 9:57am UTC
Apr 19, 2011 at 10:02am UTC
You have too many list pointers and you are getting confused using them.
First you have the global variable at line 7, then you have the local variable in function main at line
50, then you have the parameter in function void add(struct node_t at line 10.
EDIT - on another subject:
On another note, we are dealing in C++, so I would say use new instead of malloc
Last edited on Apr 19, 2011 at 10:07am UTC