问题描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
解决思路:
1.新建两个链表(head和current),一个负责保存头部最后返回,一个负责往后移动,搜罗数据;
2.待合并的两个列表,谁小谁如队列,假如只剩下一个不为空的链表,则连接到尾部直接返回。
/*
*用途:合并两个有序链表
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
//谁小谁作为表头
ListNode current;
if (l1.val <= l2.val) {
current = l1;
l1 = l1.next;
} else {
current = l2;
l2 = l2.next;
}
ListNode head = current;
while (l1 != null || l2 != null) {
if (l1 == null) {
current.next = l2;
return head;
}
if (l2 == null) {
current.next = l1;
return head;
}
if (l1.val <= l2.val) {
current.next = l1;
l1 = l1.next;
} else {
current.next = l2;
l2 = l2.next;
}
current = current.next;
}
return head;
}
leetCode提交结果: