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
            }
        }
    }
  • 相关阅读:
    svn忽略不需要同步的文件夹或文件
    Redis 字符串(String)
    Redis 数据类型
    Linux下安装rabbitMQ
    Windows平台下Git服务器搭建
    Linux下安装redis
    JVM调优总结
    Tomcat优化配置
    通过profile 用maven命令打不同配置的变量包
    Log4j日志配置说明
  • 原文地址:https://www.cnblogs.com/huangzs/p/13737939.html
Copyright © 2011-2022 走看看