S2
S2 copied to clipboard
0021. Merge Two Sorted Lists | LeetCode Cookbook
https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0021.Merge-Two-Sorted-Lists/
func mergeTwoLists(l1 *LinkList, l2 *LinkList) *LinkList {
head := &LinkList{Next:l1} //虚拟头结点
cur := head
for l1 != nil && l2 !=nil{
if l1.Val>=l2.Val{
cur.Next=l2
l2 = l2.Next
}else {
cur.Next=l1
l1 = l1.Next
}
cur = cur.Next
}
if l1 == nil{
cur.Next=l2
}else{
cur.Next=l1
}
return head.Next
}
// java -> 递归
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (null == list1) {
return list2;
}
if (null == list2) {
return list1;
}
if (list1.val <= list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
list2.next = mergeTwoLists(list2.next, list1);
return list2;
}
}