打印两个有序链表的公共部分
问题描述: 给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。 算法实现: public void printCommonPart(Node head1, Node head2) { System.out.println("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 class Node { public int value; public Node next; public Node(int value) { this.value = value; }} 算法解析: 1.仔细审题,得到问题的关键信息,像本题的“有序”、“头指针”等关键字; 2.对于当前题目,通过循环遍历,首先进行非空判断,其中任何一个头指针移动到null,过程即停止;