单链表的排序用的是冒泡法,合并借用虚指针实现两个有序链表的合并
#include<stdio.h>
#include<stdlib.h>typedef struct _list
{
int data;
struct _list *next;
}list,*Plist;
list * create_list()
{
int a;
list *s = (Plist)malloc(sizeof(list)*1);
list *L = s;
list *tmp = NULL;
while(1)
{
tmp = (list *)malloc(sizeof(list));
scanf("%d",&a);
if(a == -1)
break;
tmp->data = a;
tmp->next = NULL;
s->next = tmp;
s = s->next;
}
return L;
}
void sort_list(list *p)
{
list *pf = p->next;
list *s = p->next;
list *q = p->next;
int tmp;
bool flag=true;
while(q && q->next)
{
q=q->next;
}
while(flag)
{
flag = false;
for(s = p->next;s != q;s=s->next)
{
if(s->data > s->next->data)
{
tmp = s->data;
s->data = s->next->data;
s->next->data = tmp;
flag = true;
}
if(s->next == q)
{
pf = s;
}
}
q = pf;
}
}
list *merge_list(list *a,list *b)
{
list *head;
list *h1 = a->next;
list *h2 = b->next;
list *cur;
if(a->data > b->data)
{
head = a;
a = a->next;
}
else
{
head = b;
b = b->next;
}
cur = head;
while(h1 != NULL && h2 != NULL)
{
if(h1->data > h2->data)
{
cur->next = h2;
h2 = h2->next;
cur = cur->next;
}
else
{
cur->next = h1;
h1 = h1->next;
cur = cur->next;
}
}
if(h1 != NULL)
{
cur->next = h1;
}
if(h2 != NULL)
{
cur->next = h2;
}
return head;
}
void print_list(list *p)
{
p = p->next;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}int main()
{
list *la = create_list();
list *lb = create_list();
list *lc;
sort_list(la);
print_list(la);
sort_list(lb);
print_list(lb);
lc = merge_list(la,lb);
print_list(lc);
return 0;
}