如何使用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;
}