/** * @描述:打印两个升序链表的公共部分 * @思路: * @复杂度:时间复杂度 O(N) (N为两个链表中较长链表的长度) * @链接:https://www.nowcoder.com/practice/8943eea40dbb4185b187d80fd050fee9?tpId=101&tqId=33116&tPage=1&rp=1&ru=/ta/programmer-code-interview-guide&qru=/ta/programmer-code-interview-guide/question-ranking */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.List; class Node { private Node next; private int value; public Node(int value) { this.value = value; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public static Node createNodeList(Integer[] values) { Node head = new Node((values[0])); Node node = head; for (int i = 1; i < values.length; i++) { Node newNode = new Node(values[i]); node.next = newNode; node = newNode; } return head; } public static Node createNodeList(String[] values) { Node head = new Node(Integer.parseInt(values[0])); Node node = head; for (int i = 1; i < values.length; i++) { Node newNode = new Node(Integer.parseInt(values[i])); node.next = newNode; node = newNode; } return head; } } class PrintCommonPart { public static void printCommonPart(Node head1, Node head2) { StringBuilder builder = new StringBuilder(); Node node1 = head1; Node node2 = head2; while (node1 != null && node2 != null) { if (node1.getValue() == node2.getValue()) { builder.append(node1.getValue()).append(" "); node1 = node1.getNext(); node2 = node2.getNext(); } else if (node1.getValue() < node2.getValue()) { node1 = node1.getNext(); } else { node2 = node2.getNext(); } } System.out.print(builder.toString()); } } public class Main { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(input.readLine()); String[] strings1 = input.readLine().split(" "); Node head1 = Node.createNodeList(strings1); int m = Integer.parseInt(input.readLine()); String[] strings2 = input.readLine().split(" "); Node head2 = Node.createNodeList(strings2); PrintCommonPart.printCommonPart(head1, head2); } }