/**
* 问题:
* 打印两个有序链表的公共部分
* 给定两个有序链表的头指针head1和head2,打印出这两个链表的公共部分
* 分析:
* 因为是有序链表,所以从两个链表的头开始进行如下判断
* 1.如果head1的值小于head2的值,则head1往下移动。
* 2.如果head1的值大于head2的值,则head2往下移动。
* 3.如果head1的值等于head2的值,则打印出这个值,然后head1和head2都往下移动。
* 4.head1和head2如果有一个移动到null,则程序结束。
* @author 雪瞳
*
*/
public class Node {
public int value;
public Node next;
public Node(int data) {
this.value=data;
}
}
public class CommandPart {
public void printCommandPart(Node head1, Node head2) {
System.out.println("command part is ...");
while(head1!=null && head2!=null) {
if(head1.value == head2.value) {
System.out.println(head1.value);
head1 = head1.next;
head2 = head2.next;
}else if(head1.value > head2.value) {
head2 = head2.next;
}else if(head1.value < head2.value) {
head1 = head1.next;
}
}
}
}
public class tetsGetCommanPart {
public static void main(String[] args) {
CommandPart test = new CommandPart();
tetsGetCommanPart show = new tetsGetCommanPart();
//准备数据
Node head1 = new Node(3);
Node head2 = new Node(5);
Node n1 = new Node(11);
Node n2 = new Node(22);
Node n3 = new Node(33);
Node n4 = new Node(44);
Node n5 = new Node(55);
Node n6 = new Node(66);
Node n7 = new Node(77);
Node n8 = new Node(88);
Node n9 = new Node(99);
//连接链表
head1.next=n1;
n1.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n7;
n7.next=n9;
head2.next=n3;
n3.next=n4;
n4.next=n5;
n5.next=n8;
n8.next=n9;
show.showLink(head1);
show.showLink(head2);
test.printCommandPart(head1, head2);
}
public void showLink(Node no) {
while(no!=null) {
System.out.print(no.value+" ");
no=no.next;
}
System.out.println();
}
}
*运行结果