A Swift Solution


  • 0
    T
    /**
     * 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
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.