两个有序链表序列的交集

输入格式
输入分为两行,分别在每行给出由若干个正整数构成的非降序序列,用-1表示序列的结尾(-1不属于这个序列)。数字用空格间隔。
输出格式
在一行中输出两个输入序列的交集序列,数字间用空格分开,结尾不能有多余空格;若新链表为空,输出“NULL”(不带引号)。
输入样例
1 2 5 -1
2 4 5 8 10 -1
输出样例
2 5

算法:移动数值小的链表,如果遇到相等元素则讲元素加入到新链表,当其中任意一个链表遍历到尾部,遍历结束。

代码个人认为写得比较优美,就不进行注释了

#include<iostream>
using namespace std;
struct Node
{
	int data =0;
	Node* next = NULL;
};
typedef Node* List;
int InitList(List& list)
{
	list = new Node; 
	return 0;
}
int DestroyList(List& list)
{
	List ptr = list;
	while (ptr)
	{
		list = ptr->next;
		delete ptr;
		ptr = list;
	}
	return 0;
}
int AddNode(List& list, int data)
{
	List ptr = list;
	while (ptr->next)
		ptr = ptr->next;
	List temp = new Node;
	temp->data = data;
	ptr->next = temp;
	return 0;
}
void PrintList(const List& list)
{
	List ptr = list->next;
	if (ptr == NULL)
	{
		cout << "NULL";
		return;
	}
	while (ptr)
	{
		printf("%d ", ptr->data);
		ptr = ptr->next;
	}
}
List GetIntersection(const List& listA, const List& listB)
{
	List listC;
	InitList(listC);
	List ptrA = listA->next,
		ptrB = listB->next;
	while (ptrA&&ptrB)
	{
		if (ptrA->data < ptrB->data)
			ptrA = ptrA->next;
		else if (ptrA->data == ptrB->data)
		{
			AddNode(listC, ptrA->data);
			ptrA = ptrA->next;
			ptrB = ptrB->next;
		}
		else ptrB = ptrB->next;
	}
	return listC;
}
int main()
{
	List listA, listB;
	InitList(listA);
	InitList(listB);
	int v;
	while (cin >> v && v != -1)
		AddNode(listA, v);
	while (cin >> v && v != -1)
		AddNode(listB, v);
	List listC = GetIntersection(listA, listB);
	PrintList(listC);
	DestroyList(listA);
	DestroyList(listB);
	DestroyList(listC);
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Agreenhan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值