Created
February 20, 2018 16:47
-
-
Save benstone1/dd9889a38dd170db487d44a35678f15b to your computer and use it in GitHub Desktop.
Queue
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
class LLNode<Key> { | |
let val: Key | |
var next: LLNode? | |
init(val: Key) { | |
self.val = val | |
} | |
} | |
struct Queue<T> { | |
private var head: LLNode<T>? | |
private var tail: LLNode<T>? | |
var isEmpty: Bool { | |
return head == nil | |
} | |
mutating func enQueue(_ newElement: T) { | |
let newNode = LLNode(val: newElement) | |
guard let tail = tail else { | |
self.head = newNode | |
self.tail = newNode | |
return | |
} | |
tail.next = newNode | |
self.tail = newNode | |
} | |
mutating func deQueue() -> T? { | |
guard let oldHead = head else { | |
return nil | |
} | |
self.head = oldHead.next | |
if oldHead.next == nil { | |
self.tail = nil | |
} | |
return oldHead.val | |
} | |
func peek() -> T? { | |
return self.head?.val | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment