Last active
November 13, 2017 03:42
-
-
Save volkanbicer/93d3981842d761b14dd2a7f54d609075 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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 | |
| * } | |
| * } | |
| */ | |
| // Iterative solution | |
| func reverseList(_ head: ListNode?) -> ListNode? { | |
| var head = head | |
| var newHead: ListNode? = nil | |
| while head != nil{ | |
| var next = head?.next | |
| head?.next = newHead | |
| newHead = head | |
| head = next | |
| } | |
| return newHead | |
| } | |
| // Recursive solution | |
| func reverseList(_ head: ListNode?) -> ListNode? { | |
| return helper(head, nil) | |
| } | |
| func helper (_ head: ListNode?, _ newHead: ListNode?) -> ListNode?{ | |
| if head == nil{ | |
| return newHead | |
| } | |
| let next = head?.next | |
| head?.next = newHead | |
| return helper(next, head) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment