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
            }
        }
    }
  • 相关阅读:
    SCU 3133(博弈)
    SCU 3132(博弈)
    hdu 5183(hash)
    hdu3329(2次dfs)
    hdu5179(数位dp)
    zoj2314(有上下界的网络流)
    CF 519E(树上倍增求lca)
    hdu1251(Trie树)
    SCU 2009(数位dp)
    【Leetcode】Letter Combinations of a Phone Number
  • 原文地址:https://www.cnblogs.com/huangzs/p/13737939.html
Copyright © 2011-2022 走看看