diff --git a/Sources/LinkedList.swift b/Sources/LinkedList.swift index 62b5963..c21abaa 100644 --- a/Sources/LinkedList.swift +++ b/Sources/LinkedList.swift @@ -9,17 +9,32 @@ class LinkedList { } init?(array: [T]) { + let reversed = array.reversed() guard let first = array.first else { return nil } - self.next = LinkedList(array: Array(array.dropFirst())) + + var tailLinkedList: LinkedList? + + for i in 0 ..< reversed.count - 1 { + tailLinkedList = LinkedList(next: tailLinkedList, value: reversed.itemOnStartIndex(advancedBy: i)) + } + + self.next = tailLinkedList self.value = first } + + func array() -> Array { + if let next = next { + return [value] + next.array() + } + return [value] + } } class DoublyLinkedList { let next: DoublyLinkedList? - private(set) var previous: DoublyLinkedList? = nil + private(set) var previous: DoublyLinkedList? var head: DoublyLinkedList { guard let previous = previous else { return self @@ -29,16 +44,38 @@ class DoublyLinkedList { var value: T - init?(linkedList: LinkedList?) { - guard let element = linkedList else { + init(next: DoublyLinkedList?, value: T) { + self.value = value + self.next = next + self.next?.previous = self + } + + init?(array: [T]) { + let reversed = array.reversed() + guard let first = array.first else { return nil } - self.value = element.value - self.next = DoublyLinkedList(linkedList: element.next) + var tailDoublyLinkedList: DoublyLinkedList? + + for i in 0 ..< reversed.count - 1 { + let nextTail = DoublyLinkedList(next: tailDoublyLinkedList, value: reversed.itemOnStartIndex(advancedBy: i)) + tailDoublyLinkedList?.previous = nextTail + tailDoublyLinkedList = nextTail + } + + self.value = first + self.next = tailDoublyLinkedList self.next?.previous = self } + convenience init?(linkedList: LinkedList?) { + guard let linkedList = linkedList else { + return nil + } + self.init(array: linkedList.array()) + } + func array() -> Array { if let next = next { return [value] + next.array()