Skip to content

Commit

Permalink
Merge pull request #48 from farzadshbfn/master
Browse files Browse the repository at this point in the history
Fixes #46. Stack overflow crash.
  • Loading branch information
wokalski authored Mar 9, 2017
2 parents 7c902f8 + f622eff commit 66bfb18
Showing 1 changed file with 43 additions and 6 deletions.
49 changes: 43 additions & 6 deletions Sources/LinkedList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,32 @@ class LinkedList<T> {
}

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<T> {
if let next = next {
return [value] + next.array()
}
return [value]
}
}

class DoublyLinkedList<T> {
let next: DoublyLinkedList?
private(set) var previous: DoublyLinkedList? = nil
private(set) var previous: DoublyLinkedList?
var head: DoublyLinkedList {
guard let previous = previous else {
return self
Expand All @@ -29,16 +44,38 @@ class DoublyLinkedList<T> {

var value: T

init?(linkedList: LinkedList<T>?) {
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<T>?) {
guard let linkedList = linkedList else {
return nil
}
self.init(array: linkedList.array())
}

func array() -> Array<T> {
if let next = next {
return [value] + next.array()
Expand Down

0 comments on commit 66bfb18

Please sign in to comment.