# 左神的书——《程序员代码面试指南》之打印两个有序链表的公共部分 c++实现

//思路：
//因为是有序表，所以从两个链表的头开始进行如下判断：

#include <iostream>
using  namespace std ;
#include <cassert>

struct Node
{
int value;
struct Node * Next;

Node(int data):value(data),Next(NULL) {    }
};

{

Node *pCur1 = pHead1;
Node *pCur2 = pHead2;

while (pCur1 != NULL && pCur2 != NULL)
{
if (pCur1->value < pCur2->value)
{
pCur1 = pCur1->Next;
}
else if (pCur1->value > pCur2->value)
{
pCur2 = pCur2->Next;
}
else
{
cout << pCur2->value << " ";

pCur1 = pCur1->Next;
pCur2 = pCur2->Next;
}
}

}

int main5()
{
//这里只是单纯的分配节点，不释放节点，要不然篇幅太长了。毕竟节点的分配和释放不是重点。
Node *n1 = new Node(1);
Node *n2 = new Node(5);
Node *n3 = new Node(8);
Node *n4 = new Node(9);
Node *n5 = new Node(12);
Node *n6 = new Node(15);
Node *pHead1 = n1;
n1->Next = n2;
n2->Next = n3;
n3->Next = n4;
n4->Next = n5;
n5->Next = n6;

Node *n11 = new Node(3);
Node *n12= new Node(4);
Node *n13= new Node(5);
Node *n14= new Node(7);
Node *n15= new Node(9);
Node *n16= new Node(11);
Node *pHead2 = n11;
n11->Next = n12;
n12->Next = n13;
n13->Next = n14;
n14->Next = n15;
n15->Next = n16;

}