引言
给定两个链表,打印两个链表中的公共部分。
思路
从两个链表的第一个节点的value值开始比较,谁小移动谁。如果相等就输出,并同时移动到下一个节点。
代码
public class TwoLinkedListSame {
/**
* 链表
*/
public static class Node{
public int value;
public Node next;
public Node(int value){
this.value = value;
}
}
public static void twoLinkedListSames(Node head1, Node head2){
System.out.println("Common part:");
// 链表不为空循环
while (head1 != null && head2 != null) {
// 谁小移动谁
if(head1.value < head2.value) {
head1 = head1.next;
}else if(head2.value < head1.value){
head2 = head2.next;
// 相等打印 并同时移动
}else{
System.out.print(head1.value + ",");
head1 = head1.next;
head2 = head2.next;
}
System.out.println();
}
}
}
代码中第一个内部类是链表,方法twoLinkedListSames是打印比较方法。