输入格式
输入分为两行,分别在每行给出由若干个正整数构成的非降序序列,用-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;
}