题目
解法
class CustomLinkList {
// 头指针
public Node head;
// 当前指针
public Node current;
class Node {
// 指针
Node next;
// 值
int value;
public Node(int value) {
this.value = value;
}
}
// 添加数据
public void addData(int data) {
// 空栈
if (head == null) {
head = new Node(data);
current = head;
} else {
current.next = new Node(data);
current = current.next;
}
}
// 合并数据
public Node mergeData(Node nodeOne, Node nodeTwo) {
if (nodeOne == null && nodeTwo == null) {
return null;
}
if (nodeOne == null) {
return nodeTwo;
}
if (nodeTwo == null) {
return nodeOne;
}
Node head;
Node current;
// 设置头节点
if (nodeOne.value < nodeTwo.value) {
head = nodeOne;
current = nodeOne;
nodeOne = nodeOne.next;
} else {
head = nodeTwo;
current = nodeTwo;
nodeTwo = nodeTwo.next;
}
// 合并元素
while (nodeOne != null && nodeTwo != null) {
if (nodeOne.value < nodeTwo.value) {
current.next = nodeOne;
current = current.next;
nodeOne = nodeOne.next;
} else {
current.next = nodeTwo;
current = current.next;
nodeTwo = nodeTwo.next;
}
}
// 合并剩余的元素
if (nodeOne != null) {
current.next = nodeOne;
}
if (nodeTwo != null) {
current.next = nodeTwo;
}
return head;
}
// 打印链表
public void printData(Node head) {
Node node = head;
while (node != null) {
System.out.print("node is : " + node.data + " ");
node = node.next;
}
System.out.println();
}
}
private static void methodLink() {
CustomLinkList listOne = new CustomLinkList();
CustomLinkList listTwo = new CustomLinkList();
// 添加数据
for (int i = 0; i < 3; i++) {
listOne.addData(i);
}
for (int i = 2; i < 5; i++) {
listTwo.addData(i);
}
CustomLinkList listThree = new CustomLinkList();
listThree.head = listThree.mergeData(listOne.head, listTwo.head);
listThree.printData(listThree.head);
}
node is : 1
node is : 2
node is : 2
node is : 3
node is : 4