Swift算法之链表

214 阅读1分钟

1.斐波那切数(最佳实践-元组赋值)

func fib(_ n: Int) -> Int{
        if n < 2 {return n}
        var f1 = 0
        var f2 = 1
        for _ in 2...n {
            (f1,f2) = (f2,f1 + f2)
        }
        return f2
    }

2.链表翻转-递归法

    /**
     * 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
     *     }
     * }
     */
    
    func reverseList(_ head: ListNode?) -> ListNode? {
        if head == nil || head?.next == nil{
            return head
        }
        let newHead: ListNode? = reverseList(head?.next)
        head?.next?.next = head
        head?.next = nil
        return newHead
    }