Created
March 20, 2018 13:13
-
-
Save TerryCK/9919b8207b6056bd82bad0afe58bbd50 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
import Foundation | |
// Source: http://www.lintcode.com/en/problem/reverse-order-storage/ | |
// Question: Given 1 -> 2 -> 3 -> null, return [3,2,1]. | |
extension Collection { | |
func generatorLinkList(inital: inout LinkedListNode<Element>) { | |
reduce(into: inital) { | |
$0.nextNode = LinkedListNode(value: $1) | |
$0 = $0.nextNode! | |
} | |
} | |
} | |
class LinkedListNode<T> { | |
private(set) var value: T | |
var nextNode: LinkedListNode? | |
init(value: T, nextNode: LinkedListNode? = nil) { | |
self.value = value | |
self.nextNode = nextNode | |
} | |
} | |
var firstNodeWithIntType = LinkedListNode(value: 0) | |
var firstNodeWithCharacter = LinkedListNode(value: Character("a")) | |
(1...10).generatorLinkList(inital: &firstNodeWithIntType) | |
"ABCDEF".generatorLinkList(inital: &firstNodeWithCharacter) | |
func reversed<T>(node: LinkedListNode<T>) -> [T] { | |
switch node.nextNode { | |
case let nextNode?: return reversed(node: nextNode) + [node.value] | |
case nil : return [node.value] | |
} | |
} | |
reversed(node: firstNodeWithIntType).dropLast() | |
reversed(node: firstNodeWithCharacter).dropLast() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment