Skip to content

Instantly share code, notes, and snippets.

@volkanbicer
Last active November 13, 2017 03:42
Show Gist options
  • Select an option

  • Save volkanbicer/93d3981842d761b14dd2a7f54d609075 to your computer and use it in GitHub Desktop.

Select an option

Save volkanbicer/93d3981842d761b14dd2a7f54d609075 to your computer and use it in GitHub Desktop.
/**
* 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