从键盘输入两个链表,通过程序对他们排序,之后按递增顺序合并链表
#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
#define NULL 0
struct List
{
int data;
struct List *next;
}List;
struct List * InitList()
{
struct List *head,*p,*q;
int d;
head=(struct List *)malloc(sizeof(struct List));
head->next=NULL;
p=head;
scanf("%d",&d);
while(d>0)
{
q=(struct List *)malloc(sizeof(struct List));
q->next=NULL;
q->data=d;
p->next=q;
p=p->next;
scanf("%d",&d);
}
return head;
}
void ListChooseSort(struct List *head)
{
struct List *p,*q;
int t;
if(head->next!=NULL)
{
for(p=head->next;p->next;p=p->next)
for(q=p->next;q;q=q->next)
if(q->data
{
t=p->data;
p->data=q->data;
q->data=t;
}
}
}
struct List * UniteList(struct List *a,struct List *b)
{
struct List *U_head,*p,*q,*s;
U_head=(struct List *)malloc(sizeof(struct List));
U_head->next=NULL;
p=a->next;
q=b->next;
s=U_head;
while(p&&q)
{
if(p->data>q->data)
{
s->next=q;
q=q->next;
}
else
{
s->next=p;
p=p->next;
}
s=s->next;
}
if(p==NULL)s->next=q;
else s->next=p;
return U_head;
}
void ListPrint(struct List *head)
{
struct List *p;
p=head->next;
printf("\n\n");
while(p)
{
printf("%5d",p->data);
p=p->next;
}
printf("\n\n");
}
void main ()
{
struct List *a_head,*b_head,*Unite_head;
printf("\n创建链表a:\n\n");
a_head=InitList();
printf("\n链表a:");
ListPrint(a_head);
system("pause");
system("cls");
printf("\n创建链表b:\n\n");
b_head=InitList();
printf("\n链表b:");
ListPrint(b_head);
system("pause");
system("cls");
ListChooseSort(a_head);
printf("\n递增排序后的链表a:");
ListPrint(a_head);
ListChooseSort(b_head);
printf("递增排序后的链表b:");
ListPrint(b_head);
Unite_head=UniteList(a_head,b_head);
printf("合并后的链表为:");
ListPrint(Unite_head);
}