Skip to content

Instantly share code, notes, and snippets.

@chriswebb09
Created May 12, 2017 00:50
Show Gist options
  • Save chriswebb09/83557e0e9da94e1713457256c87461f2 to your computer and use it in GitHub Desktop.
Save chriswebb09/83557e0e9da94e1713457256c87461f2 to your computer and use it in GitHub Desktop.
Queue Data Structure
struct Queue<T> {
var list = LinkedList<T>()
mutating func enqueue(_ element: T) {
list.append(value: element)
}
mutating func dequeue() -> T? {
guard !list.isEmpty, let element = list.first else { return nil }
list.remove(node: element)
return element.value
}
func peek() -> T? {
return list.first?.value
}
var isEmpty: Bool {
return list.isEmpty
}
}
class LinkedList<T> {
public typealias Node = LLNode<T>
fileprivate var head: Node?
fileprivate var tail: Node?
var isEmpty: Bool {
return head == nil
}
var first: Node? {
return head
}
var last: Node? {
return tail
}
func append(value: T) {
let newNode = Node(value: value)
if head == nil {
head = newNode
} else if tail == nil {
tail = newNode
tail?.previous = head
head?.next = tail
} else if var tail = tail {
newNode.previous = tail
tail.next = newNode
tail = newNode
}
}
public func node(atIndex index: Int) -> Node? {
if index >= 0 {
var node = head
var i = index
while node != nil {
if i == 0 { return node }
i -= 1
node = node!.next
}
}
return nil
}
@discardableResult public func remove(node: Node) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
node.previous = nil
node.next = nil
return node.value
}
func removeAll() {
head = nil
}
@discardableResult public func removeLast() -> T {
assert(!isEmpty)
return remove(node: last!)
}
func reverse() {
var node = head
while let currentNode = node {
node = currentNode.next
swap(&currentNode.next, &currentNode.previous)
head = currentNode
}
}
}
class LLNode<T> {
var value: T
var next: LLNode?
weak var previous: LLNode?
init(value: T) {
self.value = value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment