开发者

double linke list

i am deleting a (3 or 4 th) node using double linked list...every time only first element is deleting ?what is the problem with the following code?

#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *pre;
struct node *link;
};
//void addafter(struct node*,int,int);
main()
{
struct node *p=NULL;
add(&p,2);
add(&p,3);
add(&p,4);
add(&p,5);
add(&p,6);
add(&p,27);
add(&p,8);
add(&p,9);
add(&p,10);

//addafter(&p,7,20);

delete(&p ,6);

display(&p);
}
add(struct node **q,int n)
{
struct node *temp,*r;
temp=*q;
if(temp==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->pre=NULL;
temp->data=n;
temp->link=NULL;
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *pre;
struct node *link;
};
//void addafter(struct node*,int,int);
main()
{
struct node *p=NULL;
add(&p,2);
add(&p,3);
add(&p,4);
add(&p,5);
add(&p,6);
add(&p,27);
add(&p,8);
add(&p,9);
add(&p,10);

//addafter(&p,7,20);

delete(&p ,6);

display(&p);
}
add(struct node **q,int n)
{
struct node *temp,*r;
temp=*q;
if(temp==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->pre=NULL;
temp->data=n;
temp->link=NULL;
*q=temp;
}
else
{
while(temp->link!=NULL)
temp=temp->link;
r=(struct node*)malloc(sizeof(struct node));
r->pre=temp;
r->data=n;
r->link=NULL;
temp->link=r;
}
}
/*
addafter(struct node **q,int m,int n)
{
struct node *temp,*r,*s;
int i;
temp=开发者_如何学运维*q;
for(i=1;i<m;i++)
temp=temp->link;
s=temp->link;
r=(struct node*)malloc(sizeof(struct node));
r->data=n;
r->link=temp->link;
r->pre=temp;
temp->link=r;
s->pre=r;
}
*/

/*display(struct node **q)
{
struct node *temp;
temp=*q;
while(temp!=NULL)
{
printf("\n  %d\n",temp->data);
temp=temp->link;
}
}
*/
delete(struct node **q,int n)
{
struct node *temp,*old,*s;
temp=*q;
while(temp!=NULL)
{
        if(temp->data=n)
        {
                        if(temp == *q)
                        {
                        *q=temp->link;
                        free(temp);
                        return;
                        }
                        else
                        {
                //      s=temp->link;
                         old->link=temp->link;
                //      s->pre=old; 
                        free(temp);
                         return;
                      }
        }
        else
        {
        old=temp;
        temp=temp->link;
        }

}
printf("data not found");

}
display(struct node **q)
{
struct node *temp;
temp=*q;
while(temp!=NULL)
{
printf("\n  %d\n",temp->data);
temp=temp->link;
}
}


At first glance I see this mistake:

old->link=temp->link;
temp->link->pre=temp->pre; // or old.
free(temp);

You should set the pointers for next and previous nodes too. You can make this change in your add method which is also wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜