如何使用c语言合并两个有序的单链表
- 基本思路:
创建新的头结点,使用while循环依次比较两个链表的值,并改变next的指向,破环原来两个链表的结构,当其中一个链表的指针域为NULL时循环结束,并使指针指向另一个链表就完成了新链表的创建。
- demo (IDE:vs2017)
#include<stdio.h>
struct node
{
int data;
struct node*next;
};
struct node * create(struct node *p)//尾插法创建链表
{
int x, n, i;
struct node *ph = p, *pte=p,*pta=p;
printf("请输入有序链表中结点个数:\n");
scanf("%d", &n);
printf("请顺序输入结点:\n");
for (i = 0;i < n;i++)
{
scanf("%d", &x);
pte = (struct node *)malloc(sizeof(struct node));
pte->next = NULL;
pte->data = x;
pta->next = pte;
pta = pte;
}
return ph;
}
void list(struct node *p)
{
p = p->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
struct node * merge(struct node *p1, struct node *p2)
{
struct node *pt1 = p1, *pt2=p2 , *ph ,*p;
ph = (struct node *) malloc(sizeof(struct node));
ph->next = NULL;
p = ph;
pt1 = pt1->next;pt2 = pt2->next;
while ((pt1!=NULL)&&( pt2!=NULL))
{
if ((pt1->data) <= (pt2->data))
{
p->next = pt1;
p = p->next;
pt1 = pt1->next;
}
else
{
p->next = pt2;
p = p->next;
pt2 = pt2->next;
}
}
if (pt1 != NULL)
p->next = pt1;
else
p->next = pt2;
return ph;
}
int main()
{
struct node *ph1,*ph2,*ph;
ph1 = (struct node *) malloc(sizeof(struct node));
ph2 = (struct node *) malloc(sizeof(struct node));
ph1->next = NULL;ph2->next = NULL;
ph1 = create(ph1);
ph2 = create(ph2);
ph = merge(ph1, ph2);
printf("合并后的链表:\n");
list(ph);
getchar();getchar();
return 0;
}