首页 > 试题广场 >

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

[编程题]打印两个升序链表的公共部分
  • 热度指数:5005 时间限制:C/C++ 4秒,其他语言8秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定两个升序链表,打印两个升序链表的公共部分。

输入描述:
第一个链表的长度为 n。

第二个链表的长度为 m。

链表结点的值为 val。


输出描述:
输出一行整数表示两个升序链表的公共部分的值 (按升序输出)。
示例1

输入

4
1 2 3 4
5
1 2 3 5 6

输出

1 2 3

备注:


import java.util.Scanner;

/**
 * 思路:
 * 这道题有一个很关键的部分在于【两个升序链表】
 * 那么大致思路就是,各自用一个指针指向链表,当a指针元素>b指针元素,则b指针继续往前移动,找到=a or >a的元素
 * 如果是>a,那么就轮到a指针跟上来了,直到找到相等的为止
 *
 */
class Node {

    public Node next;
    public int val;

    Node(int val) {
        this.val = val;
    }

    /**
     * 数组转链表
     * return 头结点
     */
    public static Node trans(String[] nums) {
        Node head = new Node(Integer.parseInt(nums[0]));
        Node cur = head;
        for(int i = 1; i < nums.length; i++) {
            cur.next = new Node(Integer.parseInt(nums[i]));
            cur = cur.next;
        }
        return head;
    }

    /**
     * 打印公共部分
     */
    public static void printComment(Node head1, Node head2) {
        // 用于保存要打印的值
        StringBuilder builder = new StringBuilder();
        // 退出条件:当builder不为空,而再次产生新冲突时,或任意链表被遍历完
        while (head1 != null && head2 != null) {
            if (head1.val == head2.val) {
                builder.append(head1.val).append(" ");
                head1 = head1.next;
                head2 = head2.next;
            } else if (head1.val < head2.val) {
                head1 = head1.next;
            } else {
                head2 = head2.next;
            }
        }
        System.out.println(builder.substring(0, builder.length()-1));
    }
}
public class Main {

    /**
     * 4
     * 1 2 3 4
     * 5
     * 1 2 3 5 6
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 读数字似乎没什么意义
        in.nextLine();
        String[] nums = in.nextLine().split(" ");
        Node head1 = Node.trans(nums);
        in.nextLine();
        nums = in.nextLine().split(" ");
        Node head2 = Node.trans(nums);
        Node.printComment(head1, head2);
    }

}

发表于 2020-08-26 17:51:07 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] nums1 = new int[n];
        for (int i = 0; i < n; i++) {
            nums1[i] = scan.nextInt();
        }
        int m = scan.nextInt();
        int[] nums2 = new int[m];
        for (int i = 0; i < m; i++) {
            nums2[i] = scan.nextInt();
        }
        int index1 = 0, index2 = 0;
        while (index1 < n && index2 < m) {
            if (nums1[index1] == nums2[index2]) {
                System.out.print(nums1[index1] + " ");
                index1++;
                index2++;
            } else if (nums1[index1] < nums2[index2]) {
                index1++;
            } else {
                index2++;
            }
        }
    }
}

发表于 2020-07-05 06:00:10 回复(0)