我是学习单链表操作,,,在合并上总出错,原理看了好多次,也查看了一些网上的解答,
可一做就出问题.请问应该怎样编写好.(是不是C的基础差啊)
......
#define SIZE sizeof(LinkList)
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LinkList;
.......
int main(void)
{
LinkList *sa,*sb;
sa = Creat_L(sa);
sb = Creat_L(sb);
printf("合并:\n");
sa = Merge(sa,sb);
Disp(sa);
Free(sa);
return 0;
}
LinkList *Creat_L(LinkList *L)
{
int ip = 0; //统计结点数量;
LinkList *p,*s;
if(!(L = (LinkList *)malloc(SIZE))) {printf("\n\tOut of Memory!\n"); return 0;}
L->next = NULL;
p = L;
printf("输入:");
if(!(s = (LinkList *)malloc(SIZE))) {printf("\n\tOut of Memory!\n"); return 0;}
while(scanf("%d",&s->data)==1)
{
++ ip;
s->next = NULL;
p->next = s;
p = s;
if(!(s = (LinkList *)malloc(SIZE))) {printf("\n\tOut of Memory!\n"); return 0;}
}
L->data = ip; //结点数量放入头结点;
while(getchar()!='\n') continue;
printf("\t创建完成。\n");
return L;
}
LinkList *Merge(LinkList *La,LinkList *Lb)
{
LinkList *p,*q,*s=La;
s->data = La->data + Lb->data; //将结点和放回La头结点;
p = La->next; q = Lb->next;
while(p && q)
{
if(p->data <= q->data)
{
s->next = p;
s = p;
if(p->data == q->data) q = q->next;
p = p->next;
}
else
{
s->next = q;
s = q;
q = q->next;
}
s->next = NULL;
}
s->next = p?p:q;
Free(Lb); //这个出错,不知什么问题,好象函数调用有问题?屏蔽就能通过.
return La;
}
int Disp(LinkList *L)
{
LinkList *p;
if(L->data == 0) {printf("\n这个是空链表。\n");return 0;}
else printf("有 %2d 个结点。",L->data);
p = L->next;
while(p->next)
{
printf("%3d ->",p->data);
p = p->next;
}
printf("%3d 。\n",p->data);
printf("\t显示完成。\n");
return 0;
}
void Free(LinkList *L)
{
int f = 0;
LinkList *p;
p = L;
while(p)
{
L = L->next;
free(p);
p = L;
++ f;
}
if(f) printf("\t删除完成。(含表头)共删除 %d 个。\n",f);
}