合并两个有序链表,合并以后的链表任然有序:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
void sort(struct list *l1, struct list *l2)//两个链表融合,插入排序函数
{
struct list *p1, *p2, *tmp;
p1 = l1;
p2 = l2->next;
while (p1->next&&p2)
{
if (p1->next->data > p2->data)
{
tmp = p2->next;
p2->next = p1->next;
p1->next = p2;
p2 = tmp;
}
else
{
p1 = p1->next;
}
if (p2)
{
p1->next = p2;
}
}
}
void output(struct list *head)//输出链表
{
while (head->next)
{
printf("%d", head->next->data);
head = head->next;
}
}
void input(struct list *head, int num)//输入链表
{
struct list *tmp;
struct list *end;
end = head;
printf("输入链表节点:\n");
for (int i = 0; i != num; i++)
{
tmp = (struct list*)malloc(sizeof(struct list));
scanf("%d", &tmp->data);
end->next = tmp;
tmp->next = NULL;
end = tmp;
}
}
int main()
{
int n;
list *h1, *h2;
h1 = (struct list*)malloc(sizeof(struct list));
h2 = (struct list*)malloc(sizeof(struct list));
h1->next = NULL;
h2->next = NULL;
printf("输入第一个链表的节点数:\n");
scanf("%d", &n);
printf("输入第二个链表的节点数:\n");
scanf("%d", &n);
input(h2, n);
sort(h1, h2);
output(h1);
return 0;
}