当前位置:我的异常网» C语言 » 自己编的程序,链接两个链表。但只输出第一个链表。
自己编的程序,链接两个链表。但只输出第一个链表。请你们个看看解决方案
www.myexceptions.net 网友分享于:2013-02-18 浏览:2次
自己编的程序,链接两个链表。但只输出第一个链表。请你们个看看
此程序分3个函数,一个是申请地址creat,一个是链接连个链表join,一个是输出output.输入输出结果正如下。只输出第一个链表,不知道哪里错了。我想很可能是join()的错。
#include
#include
#define LEN sizeof(struct student)
struct student
{
int num;
int score;
struct student *next;
};
int n=0;
struct student *creat(void)
{
struct student *head,*p1,*p2;
p1=p2=(struct student *)malloc(LEN);
printf( "input num,score\n ");
scanf( "%d,%d ",&p1-> num,&p1-> score);
head=NULL;
while(p1-> num!=0)
{n=n+1;
if(n==1)
head=p1;
else
p2-> next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
printf( "input num,score\n ");
scanf( "%d,%d ",&p1-> num,&p1-> score);
}
p2-> next=NULL;
return(head);
}
struct student *join(struct student *p1,struct student *p2)/*把p2连接到p1的尾部*/
{
struct student *s1;
for(s1=p1;s1-> next!=NULL;s1=s1-> next)
;
s1-> next=p2;
return(p1);
}
void output(struct student *p)
{
struct student *cur;
for(cur=p;cur!=NULL;cur=cur-> next)
printf( "No.%d score %d\n ",cur-> num,cur-> score);
}
int main()
{
struct student *lista,*listb,*list;
printf( "the one list\n ");
lista=creat();
printf( "the other list\n ");
listb=creat();
list=join(lista,listb);
printf( "\nthe join list is:\n ");
output(list);
}
输入:
the one list
input num,score
1,97
input num,score
2,45
input num,score
3,89
input num,score
0,0
the other list
input num,score
5,69
input num,score
6,93
input num,score
0,0
输出:
the join list is:
No.1 score 97
No.2 score 45
No.3 score 89
Press any key to continue
------解决方案--------------------
#include
#include
#define LEN sizeof(struct student)
struct student
{
int num;
int score;
struct student *next;
};
struct student *creat(void)
{
struct student *head,*p1,*p2;
p1=p2=(struct student *)malloc(LEN);
printf( "input num,score\n ");
scanf( "%d,%d ",&p1-> num,&p1-> score);
head=NULL;
int n=0;
while(p1-> num!=0)
{
n=n+1;
if(n==1)
head=p1;
else
p2-> next=p1;
p2=p1;
p1=(struct student *)malloc(LEN);
printf( "input num,score\n ");
scanf( "%d,%d ",&p1-> num,&p1-> score);
}
p2-> next=NULL;
return(head);
}
struct student *join(struct student *p1,struct student *p2)/*把p2连接到p1的尾部*/
{
struct student *s1;
for(s1=p1;s1-> next!=NULL;s1=s1-> next)
;
s1-> next=p2;
return(p1);
文章评论