import java.util.Scanner;
//这段代码的功能是将两个链表合并,并输出合并后的链表和原始的两个链表。
public class Main {
//定义了一个静态内部类 Node,表示链表的结点
static class Node {
int data;//表示结点的值
Node next;//表示下一个结点的引用
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Node L1 = Read(sc);
Node L2 = Read(sc);
Node L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
}
//Merge 方法用于合并两个链表
static Node Merge(Node L1, Node L2) {
if (L1 == null && L2 == null) {
return null;
}
Node p1 = L1.next;
Node p2 = L2.next;
Node L3 = new Node();
L3.next = null;
Node p3 = L3;
while (p1 != null && p2 != null) {
if (p1.data < p2.data) {
p3.next = p1;
p1 = p1.next;
} else {
p3.next = p2;
p2 = p2.next;
}
p3 = p3.next;
}
if (p1 != null) {
p3.next = p1;
}
if (p2 != null) {
p3.next = p2;
}
L1.next = null;
L2.next = null;
return L3;
}
// Read 方法用于读取输入的链表
static Node Read(Scanner sc){
int len = sc.nextInt();
if(len == 0){
return null;
}
Node h = new Node();
h.next = null;
Node last = h;
while(len > 0) {
int num = sc.nextInt();
Node node = new Node();
node.data = num;
node.next = null;
last.next = node;
last = node;
len--;
}
return h;
}
//Print 方法用于输出链表的值
static void Print(Node L) {
if (L.next == null) {
System.out.println("NULL");
return;
}
L = L.next;
while (L != null) {
System.out.print(L.data + " ");
L = L.next;
}
System.out.println();
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
class Main1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> L1 = Read(sc);
List<Integer> L2 = Read(sc);
List<Integer> L = Merge(L1, L2);
Print(L);
Print(L1);
Print(L2);
}
static List<Integer> Merge(List<Integer> L1, List<Integer> L2) {
if (L1.isEmpty() && L2.isEmpty()) {
return new ArrayList<>();
}
List<Integer> L3 = new ArrayList<>();
int i = 0;
int j = 0;
while (i < L1.size() && j < L2.size()) {
if (L1.get(i) < L2.get(j)) {
L3.add(L1.get(i));
i++;
} else {
L3.add(L2.get(j));
j++;
}
}
while (i < L1.size()) {
L3.add(L1.get(i));
i++;
}
while (j < L2.size()) {
L3.add(L2.get(j));
j++;
}
L1.clear();
L2.clear();
return L3;
}
static List<Integer> Read(Scanner sc) {
int len = sc.nextInt();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < len; i++) {
int num = sc.nextInt();
list.add(num);
}
return list;
}
static void Print(List<Integer> list) {
if (list.isEmpty()) {
System.out.println("NULL");
} else {
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
}
}
}