打印两个有序链表的公共部分【Java】

打印两个有序链表的公共部分

【题目描述】

给定两个有序链表的头指针 head1 和 head2,打印两个链表的公共部分。

【解题思路】

​ 互相比较大小,遇到相等的就输出。
在这里插入图片描述
第一次:1比5小,head1下移
第二次:2比5小,head1下移
第三次:5=5,打印,head1和head2同时下移
第四次:4比8小,head2下移

直到一方移动到null,结束整个过程。

【代码】
++++++++++++++++++++定义指针的数据结构++++++++++++++++++++++
public class Node {
    public int value;
    public Node next;
    public Node(int data){
        this.value = data;
    }
}
----------------------CommonPrint方法----------------------
public static void CommonPrint(Node head1,Node head2){
        System.out.println("Common Part:");
        while (head1.next != null && head2.next != 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();
    }
发布了58 篇原创文章 · 获赞 5 · 访问量 6293

猜你喜欢

转载自blog.csdn.net/weixin_40992982/article/details/101374740