【】【】
【题目】
给定两个有序链表的头指针 head1 和 head2,打印两个链表的公共部分
【解答】
package base;public class PrintCommonPart_P41 {void printCommonPart(Node<Integer> head1, Node<Integer> head2) {while (head1 != null && head2 != null) {// 如果 head1 的值大于 head2 的值,那么 head1 向前移动if (head1.value > head2.value) {head1 = head1.next;// 如果 head2. 的值大于 head1 的值,那么 head2 向前移动} else if (head2.value > head1.value) { head2 = head2.next;} else {System.out.println(head2.value);head2 = head2.next;head1 = head1.next;}}}
}
package base;public class Node<T> {public T value;public Node<T> next;public Node() {}public Node(T value) {this.value = value;}public boolean hasNext() {return !(this.next == null);}public void add(Node<T> node) {Node<T> temp = this;while (temp.hasNext()) {temp = temp.next;}temp.next = node;}
}