#include <stdlib.h>
#include “malloc.h”
typedef struct Linknode
{
int data;
struct Linknode *pNext;
}node,*List;
List addback(List phead,int data)//利用返回值实现尾插
{
List pnew = malloc(sizeof(pnew));
pnew->pNext = NULL;
pnew->data = data;
if(phead==NULL)
{
phead = pnew;
}
else
{
List ptemp = malloc(sizeof(ptemp));
ptemp = phead;
while(ptemp->pNext != NULL)
{
ptemp = ptemp->pNext;
}
ptemp->pNext = pnew;
}
return phead;
}
//用递归实现链表输出
void showall(List phead)
{
if(phead==NULL)
{
return;
}
else
{
printf(“%3d %p %p\n”,phead->data,phead,phead->pNext);
showall(phead->pNext);
}
}
int main()
{
List phead1=NULL;
phead1 = addback(phead1,1);
phead1 = addback(phead1,3);
phead1 = addback(phead1,5);
phead1 = addback(phead1,7);
phead1 = addback(phead1,9);
showall(phead1);
printf(“\n\n\n”);
List phead2=NULL;
phead2 = addback(phead2,2);
phead2 = addback(phead2,4);
phead2 = addback(phead2,6);
phead2 = addback(phead2,8);
phead2 = addback(phead2,10);
showall(phead2);
printf(“\n\n\n”);
List phead=NULL;
List p1=phead1;
List p2=phead2;
while(p1 != NULL || p2 != NULL)
{
if(p1 != NULL && p2 != NULL)
{
if(p1->data < p2->data)
{
phead = addback(phead,p1->data);
p1 = p1->pNext;
}
else
{
phead = addback(phead,p2->data);
p2 = p2->pNext;
}
}
else
{
while(p1 != NULL)
{
phead = addback(phead,p1->data);
p1 = p1->pNext;
}
while(p2 != NULL)
{
phead = addback(phead,p2->data);
p2 = p2->pNext;
}
break;
}
}
showall(phead);
return 0;
}
希望showall(phead)这个函数最终能顺序输出12345678910及地址,但是程序一运行到showall(phead)这个地方就终止了,不知道怎么回事,编译也没有错误。
20
好像没啥问题。
1.你那两句malloc最好强转一下:List pnew = (List)malloc(sizeof(pnew));
2.List ptemp = malloc(sizeof(ptemp));也不需要malloc(你这样直接造成内存泄漏),直接让它指向phead就行了
List addback(List phead, int data)//利用返回值实现尾插 { List pnew = (List)malloc(sizeof(pnew)); pnew->pNext = NULL; pnew->data = data; if (phead == NULL) { phead = pnew; } else { List ptemp = phead; while (ptemp->pNext != NULL) { ptemp = ptemp->pNext; } ptemp->pNext = pnew; } return phead; }