进阶实验2-3.3-两个有序链表序列的交集-编程题

01-复杂度3-二分查找-函数题

解题代码

#include<stdlib.h>
#include<stdio.h>
typedef enum{false,true} bool;
typedef struct node* pnode;
struct node {
	int data;
	pnode next;
};
pnode ReadList(pnode list);
pnode MergeList(pnode list1, pnode list2, pnode list3);
void PrintList(list);
int main()
{
	pnode list1 = NULL, list2 = NULL;
	list1 = ReadList(list1);
	list2 = ReadList(list2);
	pnode list3 = NULL;
	list3 = MergeList(list1, list2, list3);
	PrintList(list3);
	return 0;
}
pnode ReadList(pnode list) {
	pnode new, head;
	int temp_data;
	while (true) {
		scanf("%d", &temp_data);
		if (temp_data != -1) {
			if (!list) {
				head = malloc(sizeof(struct node));
				head->next = NULL;
				head->data = temp_data;
				list = head;
			}
			else {
				new = malloc(sizeof(struct node));
				new->next = NULL;
				new->data = temp_data;
				list->next = new;
				list = new;
			}
		}
		else break;
	}
	return head;
}
pnode MergeList(pnode list1, pnode list2, pnode list3) {
	pnode head = NULL, new;
	if (!list1 || !list2) return head;
	do {
		if (list1->data == list2->data) {
			if (!list3) {
				head = malloc(sizeof(struct node));
				head->next = NULL;
				head->data = list1->data;
				list3 = head;
				list1 = list1->next;
				list2 = list2->next;
			}
			else {
				new = malloc(sizeof(struct node));
				new->next = NULL;
				new->data = list1->data;
				list3->next = new;
				list3 = new;
				list1 = list1->next;
				list2 = list2->next;
			}
		}
		else if (list1->data < list2->data) list1 = list1->next;
		else list2 = list2->next;
	} while (list1&&list2);
	return head;
}
void PrintList(pnode list) {
	if (!list) {
		printf("NULL");
		return;
	}
	int flag = 1;
	do {
		if (flag) flag = 0;
		else printf(" ");
		printf("%d", list->data);
		list = list->next;
	} while (list);
}

测试结果

在这里插入图片描述

问题整理

1.这题不难。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值