要求:给出两个有序单链表的头结点 head1,head2,打印两个链表公共部分
思路:因为已经有序,所以直接比较值大小,若1小,1后移,2小,2后移,相等,打印,二者一起后移,继续比较。
public void printCommomPart(Node head1,Node head2) {
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.print(head1.value+" ");
head1 = head1.next;
head2 = head2.next;
}
}
}