Created
December 6, 2017 17:18
-
-
Save manishkkatoch/0028a637cfc6dc3207d82c104299e08d to your computer and use it in GitHub Desktop.
Queue implementation
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
// | |
// 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