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

fix(link-list): remove append of node by node in list appending method, we can append the newLinkedList head to the oldLinkedList last(tail) item. #967

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 8 additions & 8 deletions Linked List/LinkedList.playground/Contents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,9 @@ public final class LinkedList<T> {
var node = head!.next
for _ in 1..<index {
node = node?.next
if node == nil {
break
}
assert(node != nil , "index is out of bounds.")
}

assert(node != nil, "index is out of bounds.")
return node!
}
}
Expand Down Expand Up @@ -116,11 +113,12 @@ public final class LinkedList<T> {
///
/// - Parameter list: The list to be copied and appended.
public func append(_ list: LinkedList) {
var nodeToCopy = list.head
while let node = nodeToCopy {
append(node.value)
nodeToCopy = node.next

guard let headNode = list.head else {
return
}

append(headNode)
}

/// Insert a value at a specific index. Crashes if index is out of bounds (0...self.count)
Expand Down Expand Up @@ -380,13 +378,15 @@ list2.append("World")
list.append(list2) // [Hello, World, Goodbye, World]
list2.removeAll() // [ ]
list2.isEmpty // true

list.removeLast() // "World"
list.remove(at: 2) // "Goodbye"

list.insert("Swift", at: 1)
list[0] // "Hello"
list[1] // "Swift"
list[2] // "World"
//list[10] // crash!!
print(list)

list.reverse() // [World, Swift, Hello]
Expand Down