打印两个有序链表的公共部分
【题目】 给定两个有序链表的头指针 head1 和 head2,打印两个链表的公共部分。
【解答】 本题难度很低,因为是有序链表,所以从两个链表的头开始进行如下判断: 1. 如果 head1 的值小于 head2,则 head1 往下移动。 2. 如果 head2 的值小于 head1,则 head2 往下移动。 3. 如果 head1 的值与 head2 的值相等,则打印这个值,然后 head1 与 head2 都往下移动。 4. head1 或 head2 有任何一个移动到 null,则整个过程停止。 具体过程参看如下代码中的 printCommonPart 方法。
public class PrintCommonPart {
private Node head = null;
class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
}
public void add(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}
public static void printCommentPart(Node head1, Node head2) {
System.out.println("print common: ");
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;
}
}
}
public static void main(String[] args) {
PrintCommonPart list1 = new PrintCommonPart();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(4);
list1.add(4);
list1.add(5);
PrintCommonPart list2 = new PrintCommonPart();
list2.add(1);
list2.add(3);
list2.add(4);
list2.add(5);
list2.add(6);
list2.add(9);
PrintCommonPart.printCommentPart(list1.head, list2.head);
}
}
#链表##打印两个有序链表的公共部分#数据结构与算法 文章被收录于专栏
笔者学习数据结构与算法的心得与经验。
查看8道真题和解析