/
LinkedList.swift
455 lines (335 loc) · 11.7 KB
/
LinkedList.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//
// LinkedList.swift
// SwiftDataStructures
//
// Created by bryn austin bellomy on 2014 Dec 17.
// Copyright (c) 2014 bryn austin bellomy. All rights reserved.
//
import Funky
//import Respect
//
// MARK: - struct LinkedList<T> -
//
/**
`LinkedList` is intended to be used in the implementation of other collection types. To this end, it intentionally exposes some of its own implementation
details (particularly, the existence `LinkedListNode<T>`) so that developers can make use of these details to optimize the types they build on top of it.
*/
public struct LinkedList <T> //: ListType
{
public typealias InnerType = T
public typealias NodeType = LinkedListNode<T>
public private(set) var first: NodeType?
public private(set) var last: LinkedListNode<T>?
public private(set) var count: Index.Distance = 0
public init() {
}
public init(_ other:LinkedList<T>) {
extend(other)
}
public init <S: SequenceType where S.Generator.Element == NodeType> (_ nodes:S) {
extend(nodes)
}
public init <C: CollectionType where C.Generator.Element == NodeType> (_ nodes:C) {
extend(nodes)
}
public init <S: SequenceType where S.Generator.Element == T> (elements:S) {
let mapped = map(elements) { NodeType($0) }
extend(mapped)
}
/**
Returns the element at the specified index, or nil if the index was out of range.
*/
public func at(index:Index) -> Generator.Element?
{
if !contains(startIndex ..< endIndex, index) {
return nil
}
var generator = generate()
var current = first
for i in startIndex ... index {
current = generator.next()
}
precondition(current != nil, "LinkedList.at() -- Found a very unexpected nil where an element should've been.")
return current
}
/**
Returns the index of the first element for which `predicate` returns true.
*/
public func find(predicate: (LinkedListNode<T>) -> Bool) -> Index?
{
for (i, elem) in enumerate(self) {
if predicate(elem) == true {
return i
}
}
return nil
}
/**
Inserts the provided element at the beginning of the list.
*/
public mutating func prepend(newElement:NodeType) {
insert(newElement, atIndex:startIndex)
}
/**
Removes the last element from the list and returns it. The list must contain at least 1 element or a precondition will fail.
*/
public mutating func removeLast() -> NodeType {
return removeAtIndex(endIndex.predecessor())
}
}
/**
`LinkedListNode` is a type that wraps each individual element of `LinkedList`. It maintains pointers to the `next` and `previous` elements. Note that because of `LinkedList`'s dependence on pointer semantics, `LinkedListNode` is implemented (unlike most of the other data structures) as a `class`.
*/
public class LinkedListNode <T>
{
public var item: T
public private(set) var previous: LinkedListNode<T>?
public private(set) var next: LinkedListNode<T>?
public init(_ theItem:T) {
item = theItem
}
}
//
// MARK: - LinkedList: Equatable
//
public func == <T: Equatable> (lhs:LinkedList<T>, rhs:LinkedList<T>) -> Bool {
return zipseq(lhs, rhs) |> all(==)
}
public func == <T: Equatable> (lhs:LinkedListNode<T>, rhs:LinkedListNode<T>) -> Bool {
return lhs.item == rhs.item
}
//
// MARK: - LinkedList: SequenceType
//
extension LinkedList: SequenceType
{
public typealias Generator = LinkedListGenerator<T>
public func generate() -> Generator {
return Generator(self)
}
}
public struct LinkedListGenerator <T> : GeneratorType
{
public typealias Collection = LinkedList<T>
private weak var current : Collection.NodeType?
public init(_ linkedList:Collection) {
current = linkedList.first
}
public mutating func next() -> Collection.NodeType?
{
// @@TODO: i seem to recall reading in apple's swift documentation that this precondition should be enforced; however, it causes a runtime crash (on xcode 6.1.1). should investigate.
// precondition(current != nil, "next() was called too many times")
let toReturn = current
current = current?.next
return toReturn
}
}
//
// MARK: - LinkedList: MutableCollectionType
//
extension LinkedList: MutableCollectionType
{
public typealias Index = Int
public var startIndex : Index { return Index(0) }
public var endIndex : Index { return Index(count) }
public subscript(index:Index) -> Generator.Element
{
get {
precondition(index >= startIndex && index <= endIndex.predecessor(), "index is out of range.")
return at(index)!
}
set {
precondition(index >= startIndex && index <= endIndex.predecessor(), "index is out of range.")
let currentElement = self[index]
let elementBefore = currentElement.previous
let elementAfter = currentElement.next
elementBefore?.next = newValue
elementAfter?.previous = newValue
newValue.next = elementAfter
newValue.previous = elementBefore
if index == startIndex {
first = newValue
}
if index == endIndex.predecessor() {
last = newValue
}
}
}
}
//
// MARK: - LinkedList: ExtensibleCollectionType
//
extension LinkedList: ExtensibleCollectionType
{
public mutating func reserveCapacity(n: Index.Distance) {
// no-op
}
public mutating func append(newElement:NodeType) {
insert(newElement, atIndex:endIndex)
}
public mutating func extend <S : SequenceType where S.Generator.Element == T> (unwrapped sequence: S) {
let mapped = map(sequence) { NodeType($0) }
extend(mapped)
}
public mutating func extend <S : SequenceType where S.Generator.Element == NodeType> (sequence: S)
{
// Note that this should just be "for item in sequence"; this is working around a compiler crash.
for elem in [NodeType](sequence) {
append(elem)
}
}
}
//
// MARK: - LinkedList: MutableSliceable
//
extension LinkedList: MutableSliceable
{
public subscript(subrange: Range<Index>) -> LinkedList<T>
{
get
{
precondition(contains(self, subrange), "Subrange (\(subrange)) out of range.")
var subslice = LinkedList<T>()
subslice.first = self[ subrange.startIndex ]
subslice.last = self[ subrange.endIndex ]
return subslice
}
set
{
precondition(contains(self, subrange), "Subrange (\(subrange)) out of range.")
let removeLength = subrange.endIndex - subrange.startIndex
let insertLength = newValue.count
let deltaCount = insertLength - removeLength
let spliceBegin = self[subrange.startIndex]
let spliceEnd = self[subrange.endIndex]
let insertionBegin = newValue.first
let insertionEnd = newValue.last
if let previous = spliceBegin.previous {
previous.next = insertionBegin
insertionBegin?.previous = previous
}
else {
assert(spliceBegin === first)
first = insertionBegin
first?.previous = nil
}
if let next = spliceEnd.next {
next.previous = insertionEnd
insertionEnd?.next = next
}
else {
assert(spliceEnd === last)
last = newValue.last
last?.next = nil
}
count += deltaCount
}
}
}
//
// MARK: - LinkedList: RangeReplaceableCollectionType
//
extension LinkedList: RangeReplaceableCollectionType
{
public mutating func replaceRange <C: CollectionType where C.Generator.Element == NodeType>
(subrange: Range<Index>, with newElements: C)
{
var newElems = LinkedList(SequenceOf<NodeType>(newElements))
self[subrange] = newElems
}
/**
Inserts the provided element at the specified index of the list. The index must be >= startIndex and <= endIndex. Insert can therefore be used to append and prepend elements to the list (and, in fact, `append` and `prepend` simply call this function).
*/
public mutating func insert(newElement:NodeType, atIndex index:Index)
{
precondition(index >= startIndex && index <= endIndex)
newElement.previous = nil
newElement.next = nil
let currentElementAtPosition = at(index)
let elementBefore = currentElementAtPosition?.previous ?? at(index.predecessor()) ?? nil
currentElementAtPosition?.previous = newElement
elementBefore?.next = newElement
newElement.next = currentElementAtPosition
newElement.previous = elementBefore
// update first
if index == startIndex {
first = newElement
}
// update last
if index == endIndex {
last = newElement
}
++count
}
public mutating func splice <C: CollectionType where C.Generator.Element == NodeType> (newElements: C, atIndex i: Index) {
let range: Range<Index> = i ... i
replaceRange(i...i, with: newElements)
}
/**
Removes the element `n` positions from the beginning of the list and returns it. `index` must be a valid index or a precondition assertion will fail.
:param: index The index of the element to remove.
:returns: The removed element.
*/
public mutating func removeAtIndex(index:Index) -> NodeType
{
precondition(index >= startIndex && index <= endIndex.predecessor(), "index (\(index)) is out of range [startIndex = \(startIndex), endIndex = \(endIndex), count = \(count)].")
var element = self[index]
var elementBefore = element.previous
var elementAfter = element.next
if index == startIndex {
first = elementAfter
}
if index == endIndex.predecessor() {
last = elementBefore
}
elementBefore?.next = elementAfter
elementAfter?.previous = elementBefore
element.next = nil
element.previous = nil
--count
return element
}
public mutating func removeRange(subrange: Range<Index>) {
let tuple: (NodeType?, NodeType?) = removeRange(subrange)
return
}
public mutating func removeRange(subrange: Range<Index>) -> (NodeType?, NodeType?)
{
var startNode = self[subrange.startIndex]
var endNode = self[subrange.endIndex]
let (previous, subsequent) = (startNode.previous, endNode.next)
previous?.next = subsequent
subsequent?.previous = previous
count -= distance(subrange.startIndex, subrange.endIndex)
return (previous, subsequent)
}
/**
Removes all of the elements from the list. The `keepCapacity` parameter is ignored.
*/
public mutating func removeAll(#keepCapacity:Bool) {
first = nil
last = nil
count = 0
}
}
//
// MARK: - LinkedList: ArrayLiteralConvertible
//
extension LinkedList: ArrayLiteralConvertible
{
public init(arrayLiteral elements: T...) {
let wrapped = elements |> mapr { LinkedListNode($0) }
extend(wrapped)
}
}
//
// MARK: - LinkedList: Printable, DebugPrintable
//
extension LinkedList: Printable, DebugPrintable
{
public var description: String {
let arr = Array(self)
return arr.description
}
public var debugDescription: String { return description }
}