参考自:《剑指Offer——名企面试官精讲典型编程题》
题目:合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。
主要思路:比较两个链表的当前结点,找出值较小的结点,将该结点添加到新链表的尾部。该过程可通过递归实现,其中要注意链表为空的情况。
另外也可以使用一个哨兵节点,通过循环来实现。
关键点:递归
时间复杂度:O(n),n为两个链表的长度之和
public class MergeLinkedList {
public static void main(String[] args) {
int[] data1 = {2, 4, 6};
int[] data2 = {1, 3, 5};
ListNode pHead1 = LinkedListData.generateDataByArray(data1);
ListNode pHead2 = LinkedListData.generateDataByArray(data2);
// ListNode result = merge(pHead1, pHead2);
ListNode result = mergeByDummy(pHead1, pHead2);
// 1->2->3->4->5->6
while (result != null) {
System.out.printf("%d", result.val);
result = result.next;
if (result != null) {
System.out.print("->");
}
}
}
private static ListNode merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode newNode = null;
if (list1.val <= list2.val) {
newNode = list1;
newNode.next = merge(list1.next, list2);
} else {
newNode = list2;
newNode.next = merge(list1, list2.next);
}
return newNode;
}
/**
* 借助哨兵节点合并链表
*
* @param node1 the node 1
* @param node2 the node 2
* @return the list node
*/
private static ListNode mergeByDummy(ListNode node1, ListNode node2) {
//哨兵节点
ListNode dummyHead = new ListNode(0);
ListNode newNode = dummyHead;
while (node1 != null && node2 != null) {
if (node1.val < node2.val) {
newNode.next = node1;
node1 = node1.next;
} else {
newNode.next = node2;
node2 = node2.next;
}
newNode = newNode.next;
}
newNode.next = node1 == null ? node2 : node1;
return dummyHead.next;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}