目录
https://leetcode.com/problems/merge-two-sorted-lists/
将两个有序链表合并成一个有序链表后返回。
一、问题分析
测试用例:
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
在合并两个链表时,主要的麻烦在于确定哪个链表的头节点作为合并后的表头,对于这个问题,可以创建一个新节点作为合并后的头结点,在返回时将其从链表中删除即可,这样一来,可以使得头结点的处理跟其他节点一样。
二、代码实现
1、迭代版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
ListNode tempHead = new ListNode(-1);
ListNode tempTail = tempHead;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
tempTail.next = l1;
l1 = l1.next;
tempTail = tempTail.next;
} else {
tempTail.next = l2;
l2 = l2.next;
tempTail = tempTail.next;
}
}
if (l1 != null) {
tempTail.next = l1;
}
if (l2 != null) {
tempTail.next = l2;
}
// return tempHead.next;
ListNode temp = tempHead;
tempHead = tempHead.next;
temp.next = null;
return tempHead;
}
public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode head = null;
if (l1.val <= l2.val) {
head = l1;
l1 = l1.next;
} else {
head = l2;
l2 = l2.next;
}
ListNode cur = head;
ListNode temp = null;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
temp = l1;
l1 = l1.next;
temp.next = null;
} else {
temp = l2;
l2 = l2.next;
temp.next = null;
}
cur.next = temp;
cur = cur.next;
}
if (l1 != null) {
cur.next = l1;
}
if (l2 != null) {
cur.next = l2;
}
return head;
}
}
2、递归版本
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
参考:
https://leetcode.com/problems/merge-two-sorted-lists/discuss/9713/A-recursive-solution
https://leetcode.com/problems/merge-two-sorted-lists/discuss/9944/Java-recursive-solution-in-6-lines