LeetCode
题目: 合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
代码语言:javascript复制输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
代码一 迭代:
代码语言:javascript复制/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var newNode: ListNode? = nil
var newNode1 = l1
var newNode2 = l2
if newNode1!.val < newNode2!.val {
newNode = newNode1
newNode1 = newNode1?.next
} else {
newNode = newNode2
newNode2 = newNode2?.next
}
var tempNode = newNode
while (newNode1 != nil) && (newNode2 != nil) {
if newNode1!.val <= newNode2!.val {
tempNode?.next = newNode1
newNode1 = newNode1?.next
} else {
tempNode?.next = newNode2
newNode2 = newNode2?.next
}
tempNode = tempNode?.next
}
if newNode1 != nil && newNode2 == nil {
tempNode?.next = newNode1
}
if newNode1 == nil && newNode2 != nil {
tempNode?.next = newNode2
}
return newNode
}
}
代码二 递归:
代码语言:javascript复制/**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init(_ val: Int) {
* self.val = val
* self.next = nil
* }
* }
*/
class Solution {
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
if l1 == nil && l2 == nil {
return nil
}
if l1 == nil || l2 == nil {
return l1 == nil ? l2 : l1
}
var newNode: ListNode? = nil
if l1!.val <= l2!.val {
newNode = l1
newNode?.next = mergeTwoLists(l1?.next, l2)
} else {
newNode = l2
newNode?.next = mergeTwoLists(l1, l2?.next)
}
return newNode
}
}