#include<iostream>
using namespace std;
typedef struct ListNode {
int val;
struct ListNode* next;
}ListNode,*List;
void createList(List L, int n) {
ListNode* r = L;
for (int i = 0; i < n; i++) {
ListNode* p=new ListNode;
cin >> p->val;
p->next = NULL;
r->next = p;
r = r->next;
}
}
void printList(List L) {
ListNode* p = L;
while (p) {
cout << p->val<<" ";
p = p->next;
}
}
List findFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
ListNode* pa = pHead1;
ListNode* pb = pHead2;
while (pa!=pb) {
pa = (pa == nullptr )? pHead2 : pa->next;
pb = (pb == nullptr )? pHead1 : pb->next;
if (pa == nullptr || pb == nullptr)
continue;
else if (pa->val == pb->val) {
break;
}
}
return pa;
}
int main() {
int n1, n2;
List L1 = new ListNode;
L1->next = NULL;
List L2 = new ListNode;
L2->next = NULL;
cout << "请输入链表L1个数:";
cin >> n1;
createList(L1, n1);
cout << "请输入链表L2个数:";
cin >> n2;
createList(L2, n2);
cout <<"公共结点:";
printList(findFirstCommonNode(L1->next, L2->next));
cout << endl;
system("pause");
return 0;
}