206. Reverse Linked List--LeetCode Record

Tong_hdj發表於2016-07-14

Reverse a singly linked list.

/**
 * 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? {

        if head == nil || head!.next == nil {
            return head
        }

        var pre = head
        var head = head!.next
        pre!.next = nil

        while head != nil {
            var temp = head
            head = head!.next
            temp!.next = pre
            pre = temp
        }
        return pre
    }
}

相關文章