读书人

编写链表函数,复制出有序链表(小弟我已

发布时间: 2012-06-06 16:44:11 作者: rapoo

编写链表函数,复制出有序链表(我已写好好代码,但是执行结果不正确)
如题,原题是编写三个链表函数,第一个复制出相同顺序的链表,第二个复制出相反顺序的链表,第三个复制出有序链表.
代码已写好,前两个函数没问题,但是第三个执行后输出结果不正确,我怎么也找不出原因,麻烦大家给挑挑错,谢谢!

C/C++ code
#include <stdio.h> 
struct list
{
int value;
struct list *next;
};

struct list *copy1(struct list *h)
{
struct list *q,*h1,*tail1,*p;
q=h;
h1=tail1=NULL;
while(q!=NULL)
{
p=(struct list *)malloc(sizeof(struct list));
p->value=q->value;
p->next=NULL;
if(h1==NULL)
h1=tail1=p;
else
tail1=tail1->next=p;
q=q->next;
}
return h1;
}

struct list *copy2(struct list *h)
{
struct list *q,*h2,*tail2,*p;
q=h;
h2=tail2=NULL;
while(q!=NULL)
{
p=(struct list *)malloc(sizeof(struct list));
p->value=q->value;
p->next=NULL;
if(h2==NULL)
h2=tail2=p;
else
{
p->next=h2;
h2=p;
}
q=q->next;
}
return h2;
}

struct list *copy3(struct list *h)
{
struct list *q,*h3,*tail3,*u,*v,*p;
q=h;
h3=tail3=u=v=NULL;
while(q!=NULL)
{
p=(struct list *)malloc(sizeof(struct list));
p->value=q->value;
p->next=NULL;
if(h3==NULL)
u=v=h3=tail3=p;
else
{
while(v!=NULL&&v->value <p->value)
{
u=v;
v=v->next;
}
if(v!=NULL&&v!=h3)
{
p->next=v;
u->next=p;
}
if(v==h3)
{
p->next=h3;
h3=p;
}
if(v==NULL)
tail3=tail3->next=p;
}
q=q->next;
}
return h3;
}

void main()
{
struct list *h,*tail,*p;
int n,i=1;
h=tail=NULL;
printf("Input data. \n");
while(i <=6)
{
scanf("%d",&n);
p=(struct list *)malloc(sizeof(struct list));
p->value=n;
p->next=NULL;
if(h==NULL)
h=tail=p;
else
tail=tail->next=p;
i++;
}

while(1)
{
printf("****************\n1.按原来顺序复制\n2.逆序复制\n3.复制有序链表\n4.退出\n****************\n请选择功能:");
scanf("%d",&n);
if(n==1)
{
printf("新链表:");
p=copy1(h);
while(p!=NULL)
{
printf("%d\t",p->value);
p=p->next;
}
printf("\n");
}
if(n==2)
{
printf("新链表:");
p=copy2(h);
while(p!=NULL)
{
printf("%d\t",p->value);
p=p->next;
}
printf("\n");
}
if(n==3)
{
printf("新链表:");
p=copy3(h);
while(p!=NULL)
{
printf("%d\t",p->value);
p=p->next;
}
printf("\n");
}
if(n==4)
break;
}
}


[解决办法]
while(v!=NULL&&v->value<p->value)
{
u=v;
v=v->next;
}
/* v是用来寻找比p小的最后一个元素吧,每次循环后要及时把v归回到最小值。*/

读书人网 >C语言

热点推荐