Skip to content

Instantly share code, notes, and snippets.

@t0rn
Created October 25, 2018 16:18
Show Gist options
  • Save t0rn/ded3fce6e0d1f9c34a2d25b35a4453c2 to your computer and use it in GitHub Desktop.
Save t0rn/ded3fce6e0d1f9c34a2d25b35a4453c2 to your computer and use it in GitHub Desktop.
import Foundation
/// A list is either empty or it is composed of a first element (head)
/// and a tail, which is a list itself.
///
/// See http://www.enekoalonso.com/projects/99-swift-problems/#linked-lists
class List<T> {
var value: T
var nextItem: List<T>?
convenience init?(_ values: T...) {
self.init(Array(values))
}
init?(_ values: [T]) {
guard let first = values.first else {
return nil
}
value = first
nextItem = List(Array(values.suffix(from: 1)))
}
}
/*
Section rules:
Individual methods or computed properties will be added to the List<T> class as extensions to solve each problem.
Consider instances of List as immutable. All methods should return new instances of linked lists (instead of modifying the current list).
Using sequence types from the Swift Standard Library, like Array or Set is not allowed.
*/
///P01 (*) Find the last element of a linked list.
//example
extension List {
var last: T? {
guard let nextItem = nextItem,
let last = nextItem.last else {return value}
return last
}
}
List(1, 1, 2, 3, 5, 8)?.last
List(1,2,3,6)?.last
//P02 (*) Find the last but one element of a linked list.
extension List {
var pennultimate: T? {
guard let nextOfNext = nextItem?.nextItem,
let pennultimate = nextOfNext.pennultimate else {return value}
return pennultimate
}
}
//Example:
//List(1, 1, 2, 3, 5, 8)?.test()
List(1, 1, 2, 3, 5, 8)?.pennultimate
//5
List(1,2,3,6)?.pennultimate
//P03 (*) Find the Kth element of a linked list.
//By convention, the first element in the list is element 0. Use Swift subscripts to get the value from the linked list.
extension List {
subscript(index: Int) -> T? {
var list:List<T>? = self
for _ in 0..<index {
list = list?.nextItem
}
return list?.value
}
}
//Example:
let list = List(1, 1, 2, 3, 5, 8)
list?[0]
list?[1]
list?[2]
list?[3]
list?[4]
list?[5]
list?[6]
//P04 (*) Find the number of elements of a linked list.
extension List {
var length: Int {
guard let nextItem = nextItem else { return 1 }
return nextItem.length + 1
}
}
list?.length
List(1,5,7,1)?.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment