21. 合并两个有序链表
链表解题经典三把斧:
- 哑巴节点
- 栈
- 快慢指针
此题比较容易想到的解法是迭代法,生成哑巴节点,然后迭代生成后续节点。
方法一、迭代法
Swift
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {guard list1 != nil else {return list2}guard list2 != nil else {return list1}var list1 = list1var list2 = list2let dummyNode = ListNode(-1);var prev:ListNode? = dummyNodewhile list1 != nil && list2 != nil {if list1!.val < list2!.val {prev?.next = list1list1 = list1!.next}else {prev?.next = list2list2 = list2!.next}prev = prev?.next}prev?.next = (list1 != nil) ? list1 : list2return dummyNode.next}
OC
//todo
方法二、递归法
代码简洁、思路清晰、稍占内存的解法。
Swift
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {guard let list1 = list1 else { return list2 }guard let list2 = list2 else { return list1 }if list1.val < list2.val {list1.next = mergeTwoLists(list1.next, list2)return list1}else {list2.next = mergeTwoLists(list1, list2.next)return list2}}
OC
//todo