打印兩個有序鏈表的公共部分

題目:

       給定兩個有序鏈表的頭指針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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章