如何使用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-&g