思路:
1、比较两个有序链表的头部,小的作为新链表头部
2、逐步遍历两个链表,加入小的元素为新链表的下一个节点
3、新链表最后一个元素指向剩余的链表
代码:
package com.my.test.datastructure.linkedlist;
/*
* 数据结构之合并有序单链表
*/
public class MergeSortedLinkedList
{
/*
* 元素的基本定义
*/
static class Node{
/*
* value
*/
private int value;
/*
* 链表的下一个元素
*/
private Node next;
public Node (int value) {
this.value = value;
}
@Override
public String toString() {
if (this.next == null) {
return String.valueOf(this.value);
}
return this.value + "->" + this.next.toString();
}
}
/**
*
* 比较两链表的头结点,小的为新链表的头结点,分别遍历两个链表的下一个节点,小的作为新链表的下一个节点
*
*/
public static Node mergeLink(Node head1, Node head2) {
if (head1 == null && head2 == null) {
return null;
}
if (head2 == null) {
return head1;
}
if (head1 == null) {
return head2;
}
// 新链表头结点
Node newHead;
// 两个链表的指针
Node curNode1 = head1;
Node curNode2 = head2;
// 两个链表中头结点小的为新链表的头结点
if (head1.value <= head2.value) {
newHead = head1;
curNode1 = head1.next;
}
else {
newHead = head2;
curNode2 = head2.next;
}
Node tail = newHead;
// 遍历两个链表
while (curNode1 != null && curNode2 != null) {
if (curNode1.value <= curNode2.value) {
tail.next = curNode1;
curNode1 = curNode1.next;
}
else {
tail.next = curNode2;
curNode2 = curNode2.next;
}
// 更新新链表指针
tail = tail.next;
}
// 加上余下的后续链表
if (curNode1 != null) {
tail.next = curNode1;
}
if (curNode2 != null) {
tail.next = curNode2;
}
return newHead;
}
public static void main(String args[]) {
// 原链表
Node head1 = createTestLinkedList(8);
System.out.println("Origin link1: " + head1);
Node head2 = createTestLinkedList(9);
System.out.println("Origin link2: " + head2);
// 合并两个有序链表
System.out.println("Merged link: " + mergeLink(head1, head2));
}
private static Node createTestLinkedList(int len) {
Node head = new Node(0);
Node curNode = head;
for (int i = 1; i < len; i++) {
curNode.next = new Node(i);
curNode = curNode.next;
}
return head;
}
}
参考: