LinkedList - 21. Merge Two Sorted Lists

Updated on with 0 views and 0 comments
1. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

golang:

``````/**
* type ListNode struct {
*     Val int
*     Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
var res, tmp *ListNode

for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
res, tmp, l1 = connect(res, tmp, l1)
} else {
res, tmp, l2 = connect(res, tmp, l2)
}
}

res, tmp = fill(res, tmp, l1)
res, tmp = fill(res, tmp, l2)
return res
}

func connect(res, tmp, l *ListNode) (*ListNode, *ListNode, *ListNode) {
if res == nil {
res = l
tmp = l
} else {
tmp.Next = l // tmp后接l这个节点
tmp = l // tmp 后移一位
}
l = l.Next
return res, tmp, l
}

func fill(res, tmp, l *ListNode) (*ListNode, *ListNode) {
if l != nil {
if res == nil {
res = l
} else {
tmp.Next = l
}
}
return res, tmp
}
``````

java：

``````/**

* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
/* // recursion
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);
else l2.next = mergeTwoLists(l1, l2.next);

return l1.val < l2.val ? l1 : l2;
}*/

// iteratively
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = null;
ListNode temp = null;

while(l1 != null && l2 != null) {
if (l1.val < l2.val) {
if (result == null) {
result = l1;
temp = l1;
} else {
temp.next = l1;
temp = l1;
}
l1 = l1.next;
} else {
if (result == null) {
result = l2;
temp = l2;
} else {
temp.next = l2;
temp = l2;
}
l2 = l2.next;
}
}

if (l1 != null) {
if (result == null) {
result = l1;
} else {
temp.next = l1;
}

} else {
if (result == null) {
result = l2;
} else {
temp.next = l2;
}
}

return result;
}
}
``````