Skip to content

Commit 638ac36

Browse files
committed
Merge pull request kodecocodes#77 from andela-aonawale/refactor-LinkedList
Refactor linked list to make the code more Swift-like
2 parents c705bbe + cc17adc commit 638ac36

File tree

2 files changed

+5
-7
lines changed

2 files changed

+5
-7
lines changed

Linked List/LinkedList.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,10 @@ extension LinkedList: CustomStringConvertible {
158158
extension LinkedList {
159159
public func reverse() {
160160
var node = head
161-
while node != nil {
162-
swap(&node!.next, &node!.previous)
163-
head = node
164-
node = node!.previous
161+
while let currentNode = node {
162+
swap(&currentNode.next, &currentNode.previous)
163+
head = currentNode
164+
node = currentNode.previous
165165
}
166166
}
167167
}

Linked List/README.markdown

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -465,9 +465,7 @@ This loops through the entire list and simply swaps the `next` and `previous` po
465465
nil <---| |--->| |--->| |--->| |<--- head
466466
+--------+ +--------+ +--------+ +--------+
467467

468-
You may be wondering why the last statement says `node = node!.previous` to go to the next node instead of `node!.next` like you'd expect, but remember that we just swapped those pointers!
469-
470-
> **Note:** I couldn't find a way to make this code more Swift-like, without the forced unwrapping. Suggestions for improvements are welcome!
468+
You may be wondering why the last statement says `node = currentNode.previous` to go to the next node instead of `currentNode.next` like you'd expect, but remember that we just swapped those pointers!
471469

472470
Arrays have `map()` and `filter()` functions, and there's no reason why linked lists shouldn't either.
473471

0 commit comments

Comments
 (0)