欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-03-13 16:37:17
...

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);
}

测试结果

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

问题整理

1.这题不难。