题目描述:
给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。
代码:
public class printCommonPart {
public static 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(head2.value<head1.value)
{
head2 = head2.next;
}else {
System.out.print(head1.value+" ");
head1 = head1.next;
head2 = head2.next;
}
}
System.out.println();
}
}
测试代码:
public class test {
public static void main(String[] args) {
printCommonPart test = new printCommonPart();
Node head1 = new Node(0);
Node head2 = new Node(2);
Node cur = head1;
for(int i = 1;i<10;i++)
{
Node temp = new Node(i);
cur.next = temp;
cur = temp;
}
Node cur1 = head2;
for(int i = 3;i<15;i++)
{
Node temp = new Node(i);
cur1.next = temp;
cur1 = temp;
}
test.printCommonPart(head1,head2);
}
}
结果输出:
说明:
前一段时间一直在刷LeetCode的每日一题,感觉知识点太琐碎。于是准备按题型开刷,找到了左神的书,写的非常好。每天学一点,加油!