单链表的排序合并实现

单链表的排序用的是冒泡法,合并借用虚指针实现两个有序链表的合并

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值