美文网首页
206.反转链表

206.反转链表

作者: faterman | 来源:发表于2021-04-18 18:26 被阅读0次

1.正向遍历,移动指针

class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        var pre: ListNode? = nil
        var current = head
        while current != nil {
            let tmp_next = current?.next
            current?.next = pre
            pre = current
            current = tmp_next
        }
        return current
    }
}

2.递归

class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        if head == nil || head?.next == nil {
            return head
        }
        let newHead = reverseList(head?.next)
        head?.next?.next = head
        head?.next = nil
        return newHead
    }
}

相关文章

网友评论

      本文标题:206.反转链表

      本文链接:https://www.haomeiwen.com/subject/cekvlltx.html