标签:
给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。
因为是有序列表,所以从两个链表的头开始进行如下判断:
public static class Node {public int value;public Node next;
public Node(int data) {this.value = data;
}}public static void printCommonPart(Node head1, Node head2) {System.out.print("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.print(head1.value + " ");
head1 = head1.next;head2 = head2.next;}}System.out.println();}public static void printLinkedList(Node node) {System.out.print("Linked List: ");
while (node != null) {System.out.print(node.value + " ");
node = node.next;}System.out.println();}
标签:
原文地址:http://www.cnblogs.com/xiaomoxian/p/5249889.html