双向链表问题
#include<stdio.h>#include<stdlib.h>
typedef struct NODE{
struct NODE *bwd;
struct NODE *fwd;
int value;
}NODE;
insert(NODE *rootp,int value)
{
NODE *thisnode;
NODE *nextnode;
NODE *newnode;
for(thisnode=rootp;(nextnode=thisnode->fwd) !=NULL;thisnode=nextnode)
{
if(nextnode->value==value)
return 0;
else
if(nextnode->value > value)
break;
}
newnode = (NODE*)malloc(sizeof(NODE));
if(newnode == NULL)
return -1;
newnode->value=value;
newnode->fwd=nextnode;
thisnode->fwd = newnode;
if(thisnode!=rootp)
{
newnode->bwd = thisnode;
}
else
{
newnode->bwd =NULL;
}
if(nextnode!=NULL)
nextnode->bwd = newnode;
else
rootp->bwd = newnode;
return 1;
}
void main()
{
NODE *s1;
NODE *s2;
NODE *s3;
NODE *root;
root=(NODE*)malloc(sizeof(NODE));
s1=(NODE*)malloc(sizeof(NODE));
s2=(NODE*)malloc(sizeof(NODE));
s3=(NODE*)malloc(sizeof(NODE));
s1->value=5;
s2->value=12;
s3->value=15;
root->fwd=s1;
s1->bwd=NULL;
s1->fwd=s2;
s2->bwd=s1;
s3->fwd=NULL;
root->bwd=s3;
insert(root,3);
printf("%d\n",root->fwd->value);
printf("%d\n",root->fwd->fwd->value);
printf("%d\n",root->fwd->fwd->fwd->value);
printf("%d\n",root->fwd->fwd->fwd->fwd->value);
}
运行后就会出错 打印出3 5 12 这是怎么回事??