代码:
#include <iostream>
typedef class Node{
public:
int value;
Node* Next;
Node(int data):Next(NULL){
this->value = data;
}
}Node,*node;
public:
int value;
Node* Next;
Node(int data):Next(NULL){
this->value = data;
}
}Node,*node;
void printCommonpart(node &head1,node &head2){
std::cout << "链表的公共部分:" << ' ';
while(head1 != NULL&&head2!=NULL){
if(head1->value < head2->value){
head1=head1->Next;
}
else if(head1->value > head2->value){
head2=head2->Next;
}
else{
std::cout << head1->value << ' ';
head1=head1->Next;
head2=head2->Next;
std::cout << "链表的公共部分:" << ' ';
while(head1 != NULL&&head2!=NULL){
if(head1->value < head2->value){
head1=head1->Next;
}
else if(head1->value > head2->value){
head2=head2->Next;
}
else{
std::cout << head1->value << ' ';
head1=head1->Next;
head2=head2->Next;
}
}
}
int main()
{
Node *n1 = new Node(1);
int main()
{
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
Node *pHead1 = n1;
n1->Next = n2;
n2->Next = n3;
n3->Next = n4;
n4->Next = n5;
Node *n2_1 = new Node(1);
Node *n2_2= new Node(3);
Node *n2_3= new Node(5);
Node *n2_4= new Node(7);
Node *n2_5= new Node(9);
Node *pHead2 = n2_1;
n2_1->Next = n2_2;
n2_2->Next = n2_3;
n2_3->Next = n2_4;
n2_4->Next = n2_5;
n2_1->Next = n2_2;
n2_2->Next = n2_3;
n2_3->Next = n2_4;
n2_4->Next = n2_5;
printCommonpart(pHead1,pHead2);
return 0;
}
return 0;
}
测试结果: