以前写的,比较冗长。
#include <stdio.h>
#include <malloc.h>
//算法2.1 线性表的插入
struct List{
int n;
struct List *next;
};
struct List *create();
struct List *order(struct List *p1,struct List *p2);
void print(struct List *p);
int main(){
struct List *L1=(struct List*)malloc(sizeof(struct List));
struct List *L2=(struct List*)malloc(sizeof(struct List));
struct List *L3=(struct List*)malloc(sizeof(struct List));
printf("Enter the first array(enter 0 to stop):");
L1=create();
printf("\nEnter the second array:");
L2=create();
L3=order(L1,L2);
print(L3);
}
struct List *create() //有关循环条件的疑问
{ struct List *temp=(struct List*)malloc(sizeof(struct List));
struct List *p=(struct List*)malloc(sizeof(struct List));
struct List *head=(struct List*)malloc(sizeof(struct List));
head=p;
scanf("%d",&p->n);
for(;;)
{ temp=(struct List*)malloc(sizeof(struct List));
scanf("%d",&temp->n);
if(temp->n==0){p->next=NULL;break;}
p->next=temp;
p=temp;
};
/*p=NULL与p->next=NULL的不同; NULL是0x00表示指针指向一个无效地址。
因为如果指针已分配,肯定是指向一个非0x00的地址。p之前已经分配过了就不能直接再NULL了*/
return(head);
}
struct List *order(struct List *p1,struct List *p2)
{
struct List *temp=(struct List*)malloc(sizeof(struct List));
struct List *p3=(struct List*)malloc(sizeof(struct List));
struct List *head=(struct List*)malloc(sizeof(struct List));
head=p3;
if(p1->n<p2->n)
p3->n=p1->n,p1=p1->next;
else
p3->n=p2->n,p2=p2->next; //初始化p3
while(p1!=NULL&&p2!=NULL){
temp=(struct List*)malloc(sizeof(struct List));
if(p1->n < p2->n)
temp->n=p1->n,p3->next=temp,p3=temp,p1=p1->next;
else
temp->n=p2->n,p3->next=temp,p3=temp,p2=p2->next;
}
while(p1!=NULL){
temp=(struct List*)malloc(sizeof(struct List));
temp->n=p1->n,p3->next=temp,p3=temp,p1=p1->next;
}
while(p2!=NULL){
temp=(struct List*)malloc(sizeof(struct List));
temp->n=p2->n,p3->next=temp,p3=temp,p2=p2->next;
}
p3->next=NULL;
return(head);
}
void print(struct List *p)
{
while(p!=NULL)
{
printf("%3d",p->n);
p=p->next;
}
}