当前位置: 代码迷 >> 综合 >> 第二章 链表问题(打印两个有序列表的公共部分)
  详细解决方案

第二章 链表问题(打印两个有序列表的公共部分)

热度:52   发布时间:2023-10-11 12:25:09.0

【】【】

【题目】 

        给定两个有序链表的头指针 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;}
}

  相关解决方案