题目:两个有序链表,一个升序,一个降序,如何将两个链表合并成一个升序链表。如:
- 升序链表一:1->2->3->4
- 降序链表二:6->5->4->3
- 合并后结果:1->2->3->3->4->4->5->6
思考:分成两步来实现,首先将降序链表二进行反转变成升序链表,然后就可以直接对两个升序链表进行操作了。
实现:
public static void main(String[] args) {
System.out.println("初始化升序链表一");
Node head1 = initHead1();
printLinkedList(head1);
System.out.println("-------------");
System.out.println("初始化降序链表二");
Node head2 = initHead2();
printLinkedList(head2);
System.out.println("-------------");
//反转链表二
Node newHead2 = reverse(head2);
//合并两个升序链表
List<Node> nodes = merge(head1, newHead2);
for (Node node : nodes) {
System.out.println(node.value);
}
System.out.println("----合并结束-----");
}
/**
* 合并两个有序的链表
*
* @param head1 链表1的头节点
* @param head2 链表2的头结点
*/
private static List<Node> merge(Node head1, Node head2) {
List<Node> finalList = new LinkedList<>();
//循环比较两个链表的值 直到其中一个链表遍历完
if (head1 != null && head2 != null) {
while (head1.next != null && head2.next != null) {
if (head1.value < head2.value) {
finalList.add(head1);
head1 = head1.next;
} else {
finalList.add(head2);
head2 = head2.next;
}
}
}
//如果链表一还有值 直接赋值给新链表
while (head1 != null) {
finalList.add(head1);
head1 = head1.next;
}
//如果链表二还有值 直接赋值给新链表
while (head2 != null) {
finalList.add(head2);
head2 = head2.next;
}
return finalList;
}
/**
* 反转链表
*
* @param head 头结点
*/
private static Node reverse(Node head) {
if (head == null) {
return head;
}
Node curNode = head;
Node nextNode;//指向下一个要执行的Node
Node preNode = null; //指向上一个执行的Node
while (curNode != null) {
nextNode = curNode.next; //next指针后移
curNode.next = preNode; //当前Node的指针反转
preNode = curNode; // pre指针后移
curNode = nextNode;//当前Node执行反转完毕,指向当前节点的指针后移
}
return preNode;
}
public static class Node {
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
/**
* 初始化链表一 1->2->3->4
*/
private static Node initHead1() {
Node node4 = new Node(4, null);
Node node3 = new Node(3, node4);
Node node2 = new Node(2, node3);
Node node1 = new Node(1, node2);
return node1;
}
/**
* 初始化链表二 6->5->4->3
*/
private static Node initHead2() {
Node node4 = new Node(3, null);
Node node3 = new Node(4, node4);
Node node2 = new Node(5, node3);
Node node1 = new Node(6, node2);
return node1;
}
/**
* 打印链表
*/
private static void printLinkedList(Node head) {
if (head == null) return;
while (head != null) {
System.out.println(head.value);
head = head.next;
}
}
执行结果:
初始化升序链表一
1
2
3
4
-------------
初始化降序链表二
6
5
4
3
-------------
1
2
3
3
4
4
5
6
----合并结束-----