写在博客上只为了方便查看,自己第一次写,欢迎指正
/* 合并两个单向有序(升序)链表*/
#include<stdio.h>
#include<malloc.h>
typedef struct a
{
int data;
struct a *next;
}A;
A* creat(int n) // 创建单向链表(带头结点)
{
A *prior, *current, *head;
head = (A*)malloc(sizeof(A));
head->next = NULL;
while( n-->0 )
{
current = (A*)malloc(sizeof(A));
current->next = NULL;
printf("输入数据: \n");
scanf("%d", ¤t->data);
if(head->next == NULL)
head->next = current;
else
prior->next = current;
prior = current;
}
return head;
}
A *combine(A* head1, A*head2) // 合并链表,将2链表作为插入数
{
A *p1, *p2, *next1, *next2;
p1 = head1;
next1 = p1->next;
p2 = head2->next;
next2 = p2->next;
while(1)
{
if(next1->data < p2->data) // 当1链表的成员小于2链表成员时,1链表的指针指向下一个表, 2链表不动
{
p1 = next1;
next1 = p1->next;
}
if(next1 == NULL && p2 != NULL) // 当1链表先阅完时,将剩余2链表的数链接到1链表后
{
p1 ->next = p2;
break;
}
if(next1->data >= p2->data)
{
p1->next = p2;
p1 = p2;
p2->next = next1;
p2 = next2;
if(p2 == NULL)
break;
next2 = p2->next;
}
}
return head1;
}
int main(void)
{
A *head1, *head2, *p;
int n;
printf("输入1链表中的数据的个数 :");
scanf("%d", &n);
head1 = creat(n);
printf("输入2链表中的数据的个数: ");
scanf("%d", &n);
head2 = creat(n);
head1 = combine(head1, head2);
p = head1->next;
while(p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}