#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5
typedef struct list
{
int num;
struct list* next;
}LIST;
void init_list(LIST** L)
{
*L = (LIST*)malloc(sizeof(LIST));
(*L)->next = NULL;
}
void add_list(LIST* L, int num)
{
LIST* p = (LIST*)malloc(sizeof(LIST));
p->num = num;
p->next = L->next;
L->next = p;
}
void print_list(LIST* L)
{
LIST* p = L->next;
while(p!=NULL)
{
printf("%d\t", p->num);
p = p->next;
}
printf("\n");
}
LIST* merge(LIST* L1, LIST* L2)
{
LIST* L = L1;
LIST* p1 = L1->next;
LIST* p2 = L2->next;
LIST* q1;
LIST* q2;
while(p1!=NULL&&p2!=NULL)
{
q1 = p1;
p1 = p1->next;
q1->next = p2;
q2 = p2;
p2 = p2->next;
if(p1!=NULL)
q2->next = p1;
}
if(p1==NULL)
q1->next = q2;
return L;
}
LIST* merge1(LIST* L1, LIST* L2)
{
if(L1==NULL)
return L2;
else
L1->next = merge1(L2, L1->next);
return L1;
}
int main(int argc, char *argv[])
{
int i = 0;
int num = 0;
srand((unsigned int)time(NULL));
LIST* L1 = NULL;
LIST* L2 = NULL;
init_list(&L1);
init_list(&L2);
for(i=0;i<N-2;i++)
{
num = rand()%100+1;
add_list(L1, num);
}
for(i=0;i<N;i++)
{
num = rand()%100+1;
add_list(L2, num);
}
printf("list1 is:\n");
print_list(L1);
printf("list2 is:\n");
print_list(L2);
#if 0
LIST* L = merge(L1,L2);
printf("list is:\n");
print_list(L);
#endif
#if 1
L1->next = merge1(L1->next,L2->next);
printf("list is:\n");
print_list(L1);
#endif
system("PAUSE");
return 0;
}
|