步骤
- 1、同时遍历两个链表,并取出节点作比较,根据不同的情况生成新的链表
- 2、若有链表为空,则直接遍历另一个链表即可
public class CombineLinked {
private static Node head1;
private static Node tail1;
private static Node head2;
private static Node tail2;
private static Node head3;
public static void main(String[] args) {
String[] ar1 = {"1", "2", "3", "5", "18"};
String[] ar2 = {"4", "6", "10"};
for(int i = 0; i < ar1.length; i++) {
createNode1(ar1[i]);
}
System.out.println("链表1:");
printAll(head1);
for(int i = 0; i < ar2.length; i++) {
createNode2(ar2[i]);
}
System.out.println("链表2:");
printAll(head2);
System.out.println("合并后链表为:");
combine(head1, head2);
printAll(head3);
}
public static void combine(Node node1, Node node2) {
Node tail = null;
while(node1 != null && node2 != null) {
if(Integer.valueOf(node1.data) <= Integer.valueOf(node2.data)) {
if(head3 == null) {
head3 = node1;
tail = node1;
} else {
tail.next = node1;
tail = node1;
}
node1 = node1.next;
} else {
if(head3 == null) {
head3 = node2;
tail = node2;
} else {
tail.next = node2;
tail = node2;
}
node2 = node2.next;
}
}
while(node1 != null) {
if(head3 == null) {
head3 = node1;
tail = node1;
} else {
tail.next = node1;
tail = node1;
}
node1 = node1.next;
}
while(node2 != null) {
if(head3 == null) {
head3 = node2;
tail = node2;
} else {
tail.next = node2;
tail = node2;
}
node2 = node2.next;
}
}
public static void createNode1(String data) {
Node node = new Node(data);
if(head1 == null) {
head1 = node;
tail1 = node;
} else {
tail1.next = node;
tail1 = node;
}
}
public static void createNode2(String data) {
Node node = new Node(data);
if(head2 == null) {
head2 = node;
tail2 = node;
} else {
tail2.next = node;
tail2 = node;
}
}
public static void printAll(Node node) {
while(node != null) {
System.out.print(node.data + "-->");
node = node.next;
}
System.out.println();
}
static class Node{
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
}
}