1. 程式人生 > >2.1列印兩個有序連結串列的公共部分

2.1列印兩個有序連結串列的公共部分

題目

給定兩個有序連結串列的頭指標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.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; } } System.out.println(); } }