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

給定兩個有序列表的頭指針head1和head2,打印兩個鏈表的公共部分。
以下爲具體算法實現:

public class PrintCommonPart {
    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.print("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.print(head1.value+" ");
                head1=head1.next;
                head2=head2.next;
            }
        }
        System.out.println();
    }
}
發佈了56 篇原創文章 · 獲贊 108 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章