diff --git a/06-linked-list/projects/finished/LinkedList.playground/Contents.swift b/06-linked-list/projects/finished/LinkedList.playground/Contents.swift index d41e150..82817f6 100644 --- a/06-linked-list/projects/finished/LinkedList.playground/Contents.swift +++ b/06-linked-list/projects/finished/LinkedList.playground/Contents.swift @@ -38,7 +38,7 @@ example(of: "inserting at a particular index") { print("Before inserting: \(list)") var middleNode = list.node(at: 1)! for _ in 1...4 { - middleNode = list.insert(-1, after: middleNode) + middleNode = list.insert(-1, after: middleNode) ?? Node(value: 0) } print("After inserting: \(list)") } @@ -129,4 +129,20 @@ example(of: "linked list cow") { list2.remove(after: node) } print("List2: \(list2)") + + print("Append node on list2") + list2.append(4) + print("List2: \(list2)") + + print("Insert node on list2") + if let node2 = list2.node(at: 0) { + list2.insert(5, after: node2) + } + print("List2: \(list2)") + + print("Removing middle node on list2") + if let node3 = list2.node(at: 1) { + list2.remove(after: node3) + } + print("List2: \(list2)") } diff --git a/06-linked-list/projects/finished/LinkedList.playground/Sources/LinkedList.swift b/06-linked-list/projects/finished/LinkedList.playground/Sources/LinkedList.swift index ab44d82..0e49f2b 100644 --- a/06-linked-list/projects/finished/LinkedList.playground/Sources/LinkedList.swift +++ b/06-linked-list/projects/finished/LinkedList.playground/Sources/LinkedList.swift @@ -41,8 +41,8 @@ public struct LinkedList { } @discardableResult - public mutating func insert(_ value: Value, after node: Node) -> Node { - copyNodes() + public mutating func insert(_ value: Value, after node: Node) -> Node? { + guard let node = copyNodes(returningCopyOf: node) else { return nil } guard tail !== node else { append(value) return tail! @@ -117,7 +117,7 @@ public struct LinkedList { private mutating func copyNodes(returningCopyOf node: Node?) -> Node? { guard !isKnownUniquelyReferenced(&head) else { - return nil + return node } guard var oldNode = head else { return nil @@ -135,6 +135,7 @@ public struct LinkedList { newNode = newNode!.next oldNode = nextOldNode } + tail = newNode return nodeCopy }