给定两个已排序的表L1和L2 只使用基本的表操作编写计算L1∩L2的过程 交集

数据结构与算法分析——c语言描述 练习3.4 答案


#include"list.h"
#include<stdio.h>

List Intersect(List l1, List l2) {
	List intersect = CreatList();
	Position p1 = First(l1);
	Position p2 = First(l2);
	Position resultPos = intersect;
	while (p1&&p2) {
		if (Retrieve(p1) > Retrieve(p2))
			p2 = Advance(p2);
		else if (Retrieve(p1) < Retrieve(p2))
			p1 = Advance(p1);
		else {
			Insert(Retrieve(p1), resultPos);
			p1 = Advance(p1);
			p2 = Advance(p2);
			resultPos = Advance(resultPos);
		}
			
	}
	return intersect;
}

void printAll(List l) {
	Position p = Advance(l);
	while (p) {
		printf("%d ", Retrieve(p));
		p = Advance(p);
	}
}

int main() {
	List l, p;
	l = CreatList();
	p = CreatList();
	for (int i = 20; i >=0; i--)
		Insert(i, l);
	for (int i = 20; i >= 0; i-=2)
		Insert(i, p);
	printAll(Intersect(l, p));
}


你可能感兴趣的:(给定两个已排序的表L1和L2 只使用基本的表操作编写计算L1∩L2的过程 交集)