題目:
給定兩個有序鏈表的頭指針head1和head2,打印兩個鏈表的公共部分
思路:
因爲是有序鏈表,只需要從倆個鏈表的頭開始判斷
1、當head1小於head2的時候,head1向後移動
2、當head1大於head2的時候,head2向後移動
3、當head等於head2的時候,打印,head1和head2都向後移動
4、當head1或者head2中任意一個走到null,結束
.
public class test3 { public class Node { private int value; private Node next; public Node (int value){ this.value = value; } } public void printCommonPart(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 if (head1.value == head2.value){ System.out.println(head1.value +""); head1 = head1.next; head2 = head2.next; } } System.out.println(); } }