#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct LinkNode {
ElemType data;
LinkNode* next;
}LinkNode, * LinkList;
//尾插法建立单链表
void creatLinkList(LinkList& L) {
L = (LinkNode*)malloc(sizeof(LinkNode));
L->next = NULL;
LinkNode* pTail = L;
int num;
while (scanf("%d", &num) && num != -1) {
LinkNode* pnode = (LinkNode*)malloc(sizeof(LinkNode));
pnode->data = num;
pnode->next = pTail->next;
pTail->next = pnode;
pTail = pnode;
}
}
//打印输出
void printLinkList(LinkList L) {
LinkNode* pCur = L->next;
while (pCur != NULL) {
printf("%d ", pCur->data);
pCur = pCur->next;
}
}
void insertSameNum(LinkNode*& pTail, int num) {
LinkNode* pnode = (LinkNode*)malloc(sizeof(LinkNode));
pnode->data = num;
pnode->next = pTail->next;
pTail->next = pnode;
pTail = pnode;
}
//单链表求集合的交集
void SameTwoList(LinkList La, LinkList Lb, LinkList& Lc) {
LinkNode* pCurA = La->next;
LinkNode* pCurB = Lb->next;
LinkNode* pTail = Lc;
while (pCurA && pCurB) {
if (pCurA->data < pCurB->data) {
pCurA = pCurA->next;
}
else if (pCurA->data > pCurB->data) {
pCurB = pCurB->next;
}
else {
insertSameNum(pTail, pCurA->data);
pCurA = pCurA->next;
pCurB = pCurB->next;
}
}
}
int main() {
LinkList La,Lb;
creatLinkList(La);
creatLinkList(Lb);
LinkList Lc = (LinkNode*)malloc(sizeof(LinkNode));
Lc->next = NULL;
SameTwoList(La, Lb, Lc);
printLinkList(Lc);
return 0;
}