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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { var arr = [Int](), p1 = l1, p2 = l2, r = l1 while let q1 = p1, let q2 = p2 { if q1.val < q2.val { arr.append(q1.val) p1 = q1.next } else { arr.append(q2.val) p2 = q2.next } } while let q1 = p1 { arr.append(q1.val) p1 = q1.next if p1 == nil { q1.next = l2 r = l1 } } while let q2 = p2 { arr.append(q2.val) p2 = q2.next if p2 == nil { q2.next = l1 r = l2 } } p1 = r arr.forEach { p1?.val = $0 p1 = p1?.next } return r } |
❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼