编辑代码

#include <stdio.h>
#include <malloc.h>
typedef struct node   // 给结构体类型起个别名,方便之后写代码
{
	int data;
	struct node* next;
}node;
node* merge(node* l1, node* l2);
void print(node* L);
int main()
{
	// 第一个表
	node* head_1 = NULL, * tail_1, * ptr_1;
	head_1 = (node*)malloc(sizeof(node));
	tail_1 = head_1;
	int data = 0;
	scanf("%d", &data);
	while (data != -1)
	{
		ptr_1 = (node*)malloc(sizeof(node));
		ptr_1->data = data;
		tail_1->next = ptr_1;
		tail_1 = ptr_1;
		scanf("%d", &data);
	}
	tail_1->next = NULL;

	// 第二个表
	node* head_2, * tail_2, * ptr_2;
	head_2 = (node*)malloc(sizeof(node));
	tail_2 = head_2;
	scanf("%d", &data);
	while (data != -1)
	{
		ptr_2 = (node*)malloc(sizeof(node));
		ptr_2->data = data;
		tail_2->next = ptr_2;
		tail_2 = ptr_2;
		scanf("%d", &data);
	}
	tail_2->next = NULL;

	//调用合并函数
	node* head = merge(head_1->next, head_2->next);
	
	//调用打印函数
	print(head);

	return 0;
}
node* merge(node* l1, node* l2)
{
	node* head = NULL, * cur;
	head = (node*)malloc(sizeof(node));
	cur = head;
	while (l1 && l2)
	{
		if (l1->data <= l2->data)		//哪个节点数据小就连哪个
		{
			cur->next = l1;
			cur = l1;
			l1 = l1->next;
		}
		else
		{
			cur->next = l2;
			cur = l2;
			l2 = l2->next;
		}
	}
	cur->next = (l1 ? l1 : l2);		// 连接没遍历完的链表剩下的节点
	return head->next;			// 头节点不存数据,返回的是第一个存数据的节点供print函数打印
}
void print(node* L)
{
	int flag = 0;
	if (L == NULL)		// 题目说链表为空打印NULL
	{
		printf("NULL");
		return 0;
	}
	while (L != NULL)		// 对付一下pta的格式
	{
		if (flag == 0)
		{
			printf("%d", L->data);
			L = L->next;
			flag = 1;
		}
		else
		{
			printf(" %d", L->data);
			L = L->next;
		}
	}
}