zoukankan      html  css  js  c++  java
  • LeetCode合并两个有序链表Swift

    将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4

    暴力解法:

    合并为一个链表

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public var val: Int
     *     public var next: ListNode?
     *     public init() { self.val = 0; self.next = nil; }
     *     public init(_ val: Int) { self.val = val; self.next = nil; }
     *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
     * }
     */
    class Solution {
        func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            var left = l1
            var right = l2
            
            let head = ListNode.init(-1)
            var current:ListNode? = head
            
            while left != nil && right != nil {
                if left!.val > right!.val {
                    current?.next = right
                    right = right?.next
                } else {
                    current?.next = left
                    left = left?.next
                } 
                current = current?.next
            }
            current?.next = (left == nil) ? right : left
            return head.next 
        }
    }

    递归解法:

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public var val: Int
     *     public var next: ListNode?
     *     public init() { self.val = 0; self.next = nil; }
     *     public init(_ val: Int) { self.val = val; self.next = nil; }
     *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
     * }
     */
    class Solution {
        func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            guard let l1 = l1 else {
                return l2
            }
            
            guard let l2 = l2 else {
                return l1
            }
            
            if l1.val < l2.val {
                l1.next = mergeTwoLists(l1.next, l2)
                return l1
            } else {
                l2.next = mergeTwoLists(l1, l2.next)
                return l2
            }
        }
    }
  • 相关阅读:
    关于宇宙大爆炸的理论模型
    算法系列2《RSA》
    Codeforces Round #248 (Div. 1)——Nanami&#39;s Digital Board
    Cocos2d-x场景变化相关功能介绍
    NYOJ 745 蚂蚁问题(两)
    quick-cocos2d-x endToLua 退出会卡住
    编程算法
    linux基础知识1
    URAL 1553. Caves and Tunnels 树链拆分
    2014/11/13_ 随想
  • 原文地址:https://www.cnblogs.com/huangzs/p/13737939.html
Copyright © 2011-2022 走看看