![dec8e5858b796331e59d8caeee638026.png](https://i-blog.csdnimg.cn/blog_migrate/9a1e16eca265157759c855d3e45e1470.jpeg)
【解答】
本题难度很低,因为是有序链表,所以从两个链表的头开始进行如下判断:
● 如果head1的值小于head2,则head1往下移动。
● 如果head2的值小于head1,则head2往下移动。
● 如果head1的值与head2的值相等,则打印这个值,然后head1与head2都往下移动。
● head1或head2有任何一个移动到null,则整个过程停止。具体过程参看如下代码中的printCommonPart方法。
package link.example1;
public class Node {
public int value ;
public Node next;
public Node(int value){
this.value = value;
}
}
package link.example1;
public class Client {
public static void main(String[] args)
{
Node node10 = new Node(1);
Node node11= new Node(2);
Node node12 = new Node(3);
Node node13= new Node(4);
node10.next = node11;
node11.next = node12;
node12.next = node13;
Node node20 = new Node(3);
Node node21= new Node(4);
Node node22 = new Node(5);
Node node23= new Node(6);
node20.next = node21;
node21.next = node22;
node22.next = node23;printCommanPart(node10, node20);
}
private static void printCommanPart(Node node1, Node node2)
{
System.out.print("Commen part: ");
while(node1 != null && node2 != null)
{
if(node1.value > node2.value)
{
node2 = node2.next;
}else if(node1.value < node2.value)
{
node1 = node1.next;
}else{
System.out.print(node1.value+" , ");
// System.out.println("==================");
System.out.print(node2.value+" , ");
node1 = node1.next;
node2 = node2.next;
}
}
}
}