描述
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解法
- 初始解法:
这个问题转换为经典的merge排序中的merge过程. merge排序中merge操作即是将两个有序子数组合并成一个数组,需要考虑比较过程中左边右边索引到达边界的情况. 而此题是将原始的数组存储的子序列merge过程变为以链表存储的两个子有序链表的merge过程,因此想到的第一个解法为:
/**
* 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) {
ListNode left = l1;
ListNode right = l2;
ListNode header = null;
ListNode tail = header;
ListNode node = null;
while(left != null && right != null) {
if(left.val > right.val) {
if(header == null) {
header = new ListNode(right.val);
tail = header;
} else {
node = new ListNode(right.val);
tail.next = node;
tail = tail.next;
}
right = right.next;
} else {
if(header == null) {
header = new ListNode(left.val);
tail = header;
} else {
node = new ListNode(left.val);
tail.next = node;
tail = tail.next;
}
left = left.next;
}
}
//边界处理 左边子链表遍历完毕
if(left == null) {
if(tail == null) {
if(right != null) {
tail = right;
header = tail;
}
} else {
tail.next = right;
}
}
// 右边子链表遍历完毕
if(right == null) {
if(tail == null) {
if(left != null) {
tail = left;
header = tail;
}
} else {
tail.next = left;
}
}
return header;
}
}