题目:
给定两个有序链表的头指针 head1 和 head2,打印两个两个链表的公共部分。
解决思路:
从两个链表的头结点开始移动;
如果 head1 的值小于 head2,则 head1 往下移动。
如果 head2 的值小于 head1,则 head2 往下移动。
head1 或 head2 有任何一个移动到 null,结束。
public class commonPart {
public class Node{
public int value;
public Node next;
public Node(int data){
this.value = data;
}
}
public void printCommonPart(Node head1, Node head2){
System.out.println("Common part: ");
while(head1 != null && head2 != null){
if(head1.value < head2.value){
head1 = head1.next;
}else if(head1.value > head2.value){
head2 = head2.next;
}else{
System.out.println(head1.value +"");
head1 = head1.next;
head2 = head2.next;
}
}
}
public static void main(String[] args) {
}
}
参考资料:《程序员代码面试指南》左程云 著