我写的这个为什么双向链表插入和删除没有成功?
[code=C/C++][/code]
#include <stdio.h>
#include <stdlib.h>
struct num
{
int x;
struct num *next;
struct num *prior;
};
struct num *head,*temp,* tail,*p,*head1,*temp1,*tail1;
int main()
{
int x,y;
int i,j;
int *q;
temp=(struct num *)malloc(sizeof(struct num));
head=tail=temp;
temp->next=NULL;
tail->prior=NULL;
printf("请输入线性表La的长度:");
scanf("%d",&x);
printf("请输入线性表La中的元素:");
for(i=0;i<x;i++)
{
temp=(struct num *)malloc(sizeof(struct num));
scanf("%d",&temp->x);
tail->next=temp;
temp->prior=tail;
tail=temp;
tail->next=NULL;
}
printf("请输入要插入到线性表La中的数字x和插入的位置:");
scanf("%d%d",&y,&j);
temp=head->next;
tail=head;
p=(struct num*)malloc(sizeof(struct num));
p->x=y;
for(i=0;i<j;i++)
{
if(i==j)
{
p->prior=temp->prior;
temp->prior->next=p;
p->next=temp;
temp->prior=p;
}
else
{
temp=temp->next;
tail=tail->next;
}
}
temp=head->next;
printf("线性表La=");
for(i=0;i<x;i++)
{
if(i==x)
{
printf("%d\n",temp->x);
}
else
{
printf("%d ",temp->x);
temp=temp->next;
}
}
printf("请输入要删除数字的位置:");
scanf("%d",&y);
tail=head;
temp=head->next;
for(i=0;i<y;i++)
{
if(i==y)
{
tail->next=temp->next;
temp->next->prior=tail;
}
else
{
temp=temp->next;
tail=tail->next;
}
}
printf("线性表La=");
temp=head->next;
for(i=0;i<x;i++)
{
if(i==x)
{
printf("%d\n",temp->x);
}
else
{
printf("%d ",temp->x);
temp=temp->next;
}
}
printf("请输入要查找的数字:");
scanf("%d",&y);
j=0;
tail=head;
temp=head->next;
for(;temp!=NULL;)
{
if(temp->x==y)
{
printf("找到,%d在第%d个位置",y,j);
}
else
{
temp=temp->next;
j++;
}
}
printf("逆置后的线性表La=");
temp=head->next;
for(;temp->next!=NULL;)
{
temp=temp->next;
}
for(;temp!=head;)
{
if(temp->prior==head)
{
printf("%d\n",temp->x);
}
else
{
printf("%d ",temp->x);
temp=temp->prior;
}
}
printf("请输入线性表Lb的长度:");
scanf("%d",&y);
temp1=(struct num*)malloc(sizeof(struct num));
head1=tail1=temp1;
tail1->next=NULL;
tail1->prior=NULL;
printf("请输入线性表Lb中的元素:");
for(i=0;i<y;i++)
{
temp1=(struct num*)malloc(sizeof(struct num));
scanf("%d",&temp1->x);
tail1->next=temp1;
temp1->prior=tail1;
tail1=temp1;
tail1->next=NULL;
}
printf("合并La和Lb后的线性表为:");
q=(int *)malloc((x+y)*sizeof(int));
temp=head->next;
for(i=0;temp!=NULL;i++)
{
q[i]=temp->x;
temp=temp->next;
}
temp1=head1->next;
for(;temp1!=NULL;i++)
{
q[i]=temp1->x;
temp1=temp1->next;
}
for(i=0;i<x+y;i++)
for(j=1;j<x+y-i;j++)
{
if(q[j-1]>q[j])
{
y=q[j-1];
q[j-1]=q[j];
q[j]=y;
}
}
for(i=0;i<x+y;i++)
{
if(i==x+y)
{
printf("%d\n",q[i]);
}
else
{
printf("%d ",q[i]);
}
}
return 0;
}
[解决办法]
就这段循环就不对吧,循环条件是i<y,而循环判断里却加了个if (i==y)的条件,这可能跑到那个条件里么?同理上面插入的那段代码好像也是同样的错误。for(i=0;i<y;i++){ if(i==y) { tail->next=temp->next; temp->next->prior=tail; } else { temp=temp->next; tail=tail->next; }}