题目描述:
给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。
思路:注意两个链表都是有序的,如果head1的值小于head2,head1向右移动(head1 = head1.next), 如果head1的值大于head2的值,则head2向右移动(head2 = head2.next),相等则打印输出
public class Code_010_PrintCommonPart {
public static class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
}
public static void printCommonPart(Node head1, Node head2) {
System.out.print("Common: ");
while(head1 != null && head2 != null) {
if (head1.data < head2.data) {
head1 = head1.next;
} else if (head1.data > head2.data) {
head2 = head2.next;
} else {
System.out.print(head1.data + " ");
head1 = head1.next;
head2 = head2.next;
}
}
}
}