Created
December 28, 2019 16:37
-
-
Save marcuswestin/b80d5865dff7a44e2cf309c712dcd846 to your computer and use it in GitHub Desktop.
Linked List in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class LinkedList<T> { | |
private class Link<T> { | |
var prev: Link? | |
var next: Link? | |
let value: T | |
init(_ value: T) { | |
self.value = value | |
} | |
} | |
private var _first: Link<T>? | |
private var _last: Link<T>? | |
var first: T { get { return _first!.value }} | |
var last: T { get { return _last!.value }} | |
func isEmpty() -> Bool { | |
return _first == nil | |
} | |
func hasContent() -> Bool { | |
return _first != nil | |
} | |
func add(beforeFirst value: T) { | |
let newFirst = Link(value) | |
if isEmpty() { | |
_first = newFirst | |
_last = newFirst | |
} else { | |
newFirst.prev = _first | |
_first!.next = newFirst | |
_first = newFirst | |
} | |
} | |
func add(afterLast value: T) { | |
let newLast = Link(value) | |
if isEmpty() { | |
_last = newLast | |
_first = newLast | |
} else { | |
newLast.next = _last | |
_last!.prev = newLast | |
_last = newLast | |
} | |
} | |
@discardableResult | |
func removeFirst() -> T { | |
let value = _first!.value | |
_first = _first!.prev | |
return value | |
} | |
@discardableResult | |
func removeLast() -> T { | |
let value = _last!.value | |
_last = _last!.next | |
return value | |
} | |
func enumerate(_ enumeratorFn: (T) -> Void) { | |
var link = _last | |
while link != nil { | |
enumeratorFn(link!.value) | |
link = link!.next | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment