#include<stdio.h>
#include<stdlib.h>
typedef struct Queue
{
int data;
struct Queue *next;
}Queue,* LinkQueue;
Queue *InitQueue()
{
Queue *queue = (Queue *)malloc(sizeof(Queue));
if(queue == NULL)
{
printf("create fail \n");
return 0;
}
queue->next = NULL;
return queue;
}
void EnQueue(Queue *queue , int data)
{
Queue *tmp = (Queue *)malloc(sizeof(Queue));
while(queue->next != NULL)
{
queue = queue->next;
}
tmp->data = data ;
queue->next = tmp;
tmp->next = NULL;
}
void printfall(Queue *queue)
{
while(queue->next != NULL)
{
printf("%5d",queue->next->data);
queue = queue->next ;
}
}
Queue *merge(Queue *list1, Queue *list2)
{
Queue *list3 = InitQueue();
while(list1->next!= NULL && list2->next !=NULL)
{
if(list1->next->data > list2->next->data)
{
EnQueue(list3,list2->next->data);
list2 = list2->next;
}
else if(list1->next->data <= list2->next->data)
{
EnQueue(list3,list1->next->data);
list1=list1->next;
}
if(list1->next == NULL)
{
while(list2->next!=NULL)
{
EnQueue(list3,list2->next->data);
list2 = list2->next;
}
}
else if(list2->next == NULL)
{
while(list1->next!=NULL)
{
EnQueue(list3,list1->next->data);
list1 = list1->next;
}
}
}
return list3;
}
int main()
{
int i ;
int a[] = {13,27,38,49,65,76,97};
int b[] = {1,2,3,49,70,75,97};
Queue *list1 = InitQueue();
Queue *list2 = InitQueue();
for(i = 0 ; i < sizeof(a)/sizeof(a[0]);i++)
{
EnQueue(list1,a[i]);
}
for(i = 0 ;i < sizeof(b)/sizeof(b[0]);i++ )
{
EnQueue(list2,b[i]);
}
printfall(merge(list1,list2));
return 0;
}
运行结果:
|