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

给定两个升序链表,打印两个升序链表的公共部分。

常规题目,感觉也没什么好说的。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

class Node {
    public int val;
    public Node next;
    public Node(int val) {
        this.val = val;
    }
}

public class Main {
    public static void printCommonPart(Node head1, Node head2) {
        if (head1 == null || head2 == null) {
            return;
        }
        Node n1 = head1;
        Node n2 = head2;
        while (n1 != null && n2 != null) {
            if (n1.val == n2.val) {
                System.out.print(n1.val + " ");
            }
            if (n1.val < n2.val) {
                n1 = n1.next;
            } else {
                n2 = n2.next;
            }
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int num1 = Integer.parseInt(bf.readLine());
        String[] elems1 = bf.readLine().split(" ");
        Node list1 = new Node(Integer.parseInt(elems1[0]));
        Node head1 = list1;
        for (int i = 1; i < elems1.length; i++) {
            list1.next = new Node(Integer.parseInt(elems1[i]));
            list1 = list1.next;
        }
        int num2 = Integer.parseInt(bf.readLine());
        String[] elems2 = bf.readLine().split(" ");
        Node list2 = new Node(Integer.parseInt(elems2[0]));
        Node head2 = list2;
        for (int i = 1; i < elems2.length; i++) {
            list2.next = new Node(Integer.parseInt(elems2[i]));
            list2 = list2.next;
        }
        printCommonPart(head1, head2);
    }
}

你可能感兴趣的:(算法与数据结构)