两个有序的链表合并成一个【C语言】

比如:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
	int data;
	struct Node* next;
} Node, *LinkedList;

// 创建一个新节点
Node* createNode(int data) {
	Node* newNode = (Node*)malloc(sizeof(Node));
	if (newNode == NULL) {
		printf("Error! Unable to create a new node.\n");
		exit(0);
	}
	newNode->data = data;
	newNode->next = NULL;
	return newNode;
}

// 在链表末尾添加新节点
void append(LinkedList* head, int data) {
	if (*head == NULL) {
		*head = createNode(data);
	}
	else {
		Node* lastNode = *head;
		while (lastNode->next != NULL) {
			lastNode = lastNode->next;
		}
		lastNode->next = createNode(data);
	}
}

// 打印链表
void printList(LinkedList head) {
	while (head != NULL) {
		printf("%d ", head->data);
		head = head->next;
	}
	printf("\n");
}

LinkedList mergeTwoLists(Node* head1, Node* head2)
{
	if (head1 == NULL)
	{
		return head2;
	}
	if (head2 == NULL)
	{
		return head1;
	}

	Node *newList = NULL;  //创建新的链表,把数据排序进去
	Node *curList = NULL;
	newList = curList = (Node *)malloc(sizeof(Node));

	while (head1 && head2)
	{
		if (head1->data > head2->data)
		{
			curList->next = head2;
			head2 = head2->next;
		}
		else
		{
			curList->next = head1;
			head1 = head1->next;
		}
		curList = curList->next;
	}
	if (head1)
	{
		curList->next = head1;
	}
	else
	{
		curList->next = head2;
	}
	Node* p = newList;
	newList = newList->next;
	free(p);   //释放申请的空间
	return newList;
}

int main() {
	LinkedList head1 = NULL;
	append(&head1, 1);
	append(&head1, 3);
	append(&head1, 4);
	append(&head1, 6);

	LinkedList head2 = NULL;
	append(&head2, 1);
	append(&head2, 2);
	append(&head2, 5);
	append(&head2, 7);

	printf("Original List1: ");
	printList(head1);
	printf("Original List2: ");
	printList(head2);

	LinkedList head = mergeTwoLists(head1, head2);

	printf("mergeTwoLists List: ");
	printList(head);
	system("pause");
	return 0;
}

这个是比较详细的说明:https://mp.weixin.qq.com/s/0TiG9cF_la77aW_jUZf53w

CSDN:https://blog.csdn.net/efls111/article/details/134351938

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值