Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed some missing points in linked list example #5

Open
wants to merge 3 commits into
base: editions/4.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
}
Expand Down Expand Up @@ -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)")
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ public struct LinkedList<Value> {
}

@discardableResult
public mutating func insert(_ value: Value, after node: Node<Value>) -> Node<Value> {
copyNodes()
public mutating func insert(_ value: Value, after node: Node<Value>) -> Node<Value>? {
guard let node = copyNodes(returningCopyOf: node) else { return nil }
guard tail !== node else {
append(value)
return tail!
Expand Down Expand Up @@ -117,7 +117,7 @@ public struct LinkedList<Value> {

private mutating func copyNodes(returningCopyOf node: Node<Value>?) -> Node<Value>? {
guard !isKnownUniquelyReferenced(&head) else {
return nil
return node
}
guard var oldNode = head else {
return nil
Expand All @@ -135,6 +135,7 @@ public struct LinkedList<Value> {
newNode = newNode!.next
oldNode = nextOldNode
}
tail = newNode

return nodeCopy
}
Expand Down