Created
October 29, 2020 10:12
-
-
Save Rag0n/0febaa6bb4db3ddc27c5924b7c447467 to your computer and use it in GitHub Desktop.
Linked list
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
public final class LinkedList<T> { | |
public final class Node<T> { | |
public private(set) var value: T | |
public var next: Node? | |
public init(value: T) { | |
self.value = value | |
} | |
} | |
public init(nodes: [T]) { | |
let listNodes = nodes.map(Node.init(value:)) | |
var node = listNodes.first | |
head = node | |
listNodes.dropFirst().forEach { next in | |
node?.next = next | |
node = next | |
} | |
} | |
private var head: Node<T>? | |
public var isEmpty: Bool { | |
return head == nil | |
} | |
public var first: Node<T>? { | |
return head | |
} | |
} | |
extension LinkedList.Node: CustomStringConvertible { | |
public var description: String { | |
return "Node \(value)" | |
} | |
} | |
extension LinkedList: CustomStringConvertible { | |
public var description: String { | |
guard var node = head else { return "Empty list" } | |
var result = "\(node.value)" | |
while let next = node.next { | |
node = next | |
result.append(", \(node.value)") | |
} | |
result.insert("[", at: result.startIndex) | |
result.insert("]", at: result.endIndex) | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment