I use lists a lot
// Created by frank on 1/15/19. <span style="font-size: 14pt;">// Copyright © 2019 frank. All rights reserved. // import Foundation public class Node<T> { var value: T var next: Node<T>? weak var previous: Node<T>? init(value: T) { self.value = value } } public class LinkedList<T> { fileprivate var head: Node<T>? private var tail: Node<T>? private var currentNode: Node<T>? public var isEmpty: Bool { return head == nil } public var first: Node<T>? { return head } public var last: Node<T>? { return tail } public var current: Node<T>? { return currentNode } public func currentValue() -> T { if currentNode == nil{ currentNode = head } let tValue = currentNode?.value currentNode = currentNode?.next return tValue! } public func currentIndexValue(index: Int) -> T { var node = head var count = 0 while node != nil { if count == index{ break } node = node!.next count = count + 1 } return (node?.value)! } public func getNext() -> String { var text = "" text = "\(currentNode!.value)" currentNode = currentNode?.next if currentNode == nil{ currentNode = head } return text } public func append(value: T) { let newNode = Node(value: value) if let tailNode = tail { newNode.previous = tailNode tailNode.next = newNode } else { head = newNode currentNode = head } tail = newNode } public func nodeAt(index: Int) -> Node<T>? { if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } public func removeAll() { head = nil tail = nil } public func getCount()->Int{ var node = head var ecount = 0 while node != nil { //text += "\(node!.value)" node = node!.next //if node != nil { text += ", " } ecount = ecount + 1 } return ecount } public func remove(node: Node<T>) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev if next == nil { tail = prev } node.previous = nil node.next = nil return node.value } } extension LinkedList: CustomStringConvertible { public var description: String { var text = "[" var node = head while node != nil { text += "\(node!.value)" node = node!.next if node != nil { text += ", " } } return text + "]" } }