C語言:合併兩個有序的單鏈表

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

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章