美文网首页
11.LeetCode刷题For Swift·206. 反转链表

11.LeetCode刷题For Swift·206. 反转链表

作者: 富城 | 来源:发表于2020-12-28 10:21 被阅读0次

1、原题

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

2、思路

3、代码

/**
 * 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
 *     }
 * }
 */
class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        var head = head
        var newHead: ListNode? = nil

        while head != nil {
            let tmp = head?.next
            head?.next = newHead
            newHead = head
            head = tmp
        }
        return newHead
    }
}

相关文章

网友评论

      本文标题:11.LeetCode刷题For Swift·206. 反转链表

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