Skip to content

Instantly share code, notes, and snippets.

@manishkkatoch
Created December 6, 2017 17:18
Show Gist options
  • Save manishkkatoch/0028a637cfc6dc3207d82c104299e08d to your computer and use it in GitHub Desktop.
Save manishkkatoch/0028a637cfc6dc3207d82c104299e08d to your computer and use it in GitHub Desktop.
Queue implementation
//
// Queue.swift
// mockLocation
//
// Created by Manish Katoch on 11/29/17.
// Copyright © 2017 Manish Katoch. All rights reserved.
//
import Foundation
import CoreLocation
fileprivate class Node<T> {
let item: T
var next: Node<T>?
init(with item: T) {
self.item = item
self.next = nil
}
}
fileprivate class UniDirectionalLinkedList<T> {
fileprivate var head: Node<T>?
private var tail: Node<T>?
func isEmpty() -> Bool {
return head == nil
}
func append(_ item: T) {
let node = Node(with: item)
if let lastNode = tail {
lastNode.next = node
} else {
head = node
}
tail = node
}
}
struct Queue<T> {
private let linkedList = UniDirectionalLinkedList<T>()
func enqueue(_ item: T) {
linkedList.append(item)
}
func dequeue() -> T? {
guard let head = linkedList.head else {
return nil
}
linkedList.head = head.next
return head.item
}
func isEmpty() -> Bool {
return linkedList.isEmpty()
}
func peek() -> T? {
return linkedList.head?.item
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment