Skip to content

Instantly share code, notes, and snippets.

@matthewcheok
Created July 31, 2015 04:39
Show Gist options
  • Save matthewcheok/42dd37b3aa6a555f37e0 to your computer and use it in GitHub Desktop.
Save matthewcheok/42dd37b3aa6a555f37e0 to your computer and use it in GitHub Desktop.
Linked List
class NodeImpl {
var node: Node?
func copy() -> NodeImpl {
let copy = NodeImpl()
copy.node = node
return copy
}
}
struct Node: CustomStringConvertible {
var impl = NodeImpl()
var value: Int
var next: Node? {
get {
return impl.node
}
set {
if !isUniquelyReferencedNonObjC(&impl) {
impl = impl.copy()
}
impl.node = newValue
}
}
init(_ value: Int, next: Node?) {
self.value = value
self.next = next
}
var description: String {
if let next = next {
return "\(value) -> \(next)"
}
else {
return "\(value) -> X"
}
}
}
let n = Node(2, next: nil)
print(n)
let m = Node(6, next: n)
print(m)
var z = m
z.value = 8
z.next = m
print(z)
print(m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment