链表在子函数中用malloc申请个链表的头,但传不回主函数,主函数中的lc仍然没变
#include<stdio.h>#include<stdlib.h>
struct list
{
int data;
list *next;
};
typedef list List;
void inist_list(List *l)
{
List *p,*s;
int n;
l->next=NULL;
p=l;
printf("What do you want to add the number:\n");
scanf("%d",&n);
while(n>0)
{
s=(List *)malloc(sizeof(List));
printf("please input your data:\n");
scanf("%d",&s->data);
s->next=NULL;
p->next=s;
p=s;
n--;
}
}
void union_lc(List *la,List *lb,List *lc)
{
int temp;
List *p,*s,*p1,*p2;
// lc=(List *)malloc(sizeof(List)); //在这申请lc的头节点在主函数中不能改变
lc->next=NULL;
p=lc;
p1=la->next;
p2=lb->next;
while(p1->next!=NULL&&p2->next!=NULL)
{
if(p1->data<p2->data)
{
s=(List *)malloc(sizeof(List));
s->data=p1->data;
s->next=NULL;
p->next=s;
p=s;
p1=p1->next;
}
else
{
s=(List*)malloc(sizeof(List));
s->data=p2->data;
s->next=NULL;
p->next=s;
p=s;
p2=p2->next;
}
}
while(p1!=NULL)
{
s=(List*)malloc(sizeof(List));
s->data=p1->data;
s->next=NULL;
p->next=s;
p=s;
p1=p1->next;
}
while(p2!=NULL)
{
s=(List*)malloc(sizeof(List));
s->data=p2->data;
s->next=NULL;
p->next=s;
p=s;
p2=p2->next;
}
}
void display(List *lc)
{
List *p;
p=lc->next;
while(p!=NULL)
{
printf("%8d",p->data);
p=p->next;
}
printf("\n");
}
int main()
{
List *la,*lb,*lc;
la=(List *)malloc(sizeof(List));
lb=(List *)malloc(sizeof(List));
lc=(List *)malloc(sizeof(List)); //为什么非要把这个放到这,放到上述位置就错了,返回到主函数时,lc没有被改变
printf("This is la.\n");
inist_list(la);
printf("This is lb.\n");
inist_list(lb);
union_lc(la,lb,lc);
display(lc);
List *p,*q;
q=la;
p=la->next;
while(p!=NULL)
{
free(q);
q=p;
p=p->next;
}
q=lb;
p=lb->next;
while(p!=NULL)
{
free(q);
q=p;
p=p->next;
}
q=lc;
p=lc->next;
while(p!=NULL)
{
free(q);
q=p;
p=p->next;
}
p=NULL;
q=NULL;
return 0;
}
[ 本帖最后由 小菜小C 于 2011-7-18 10:29 编辑 ]