Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created May 13, 2022 21:02
Show Gist options
  • Save derekli66/e2d19342329f341c8830871b59670b54 to your computer and use it in GitHub Desktop.
Save derekli66/e2d19342329f341c8830871b59670b54 to your computer and use it in GitHub Desktop.
Solution to LeetCode problem, 225 Implement Stack using Queues. https://leetcode.com/problems/implement-stack-using-queues/
class ListNode {
var next: ListNode?
var key: Int = 0
}
/*
push to back, peek/pop from front, size and is empty
*/
class LinkedList {
private var head: ListNode?
private var tail: ListNode?
private var count: Int = 0
func push(_ key: Int) {
let newNode = ListNode()
newNode.key = key
if head == nil {
head = newNode
tail = newNode
}
else {
tail?.next = newNode
tail = tail?.next
}
count += 1
}
func peak() -> Int {
return head?.key ?? 0
}
func popFront() -> Int {
let frontNode = head
head = head?.next
if head == nil {
tail = nil
}
count -= 1
return frontNode?.key ?? 0
}
func size() -> Int {
return count
}
func isEmpty() -> Bool {
return size() == 0
}
}
class MyStack {
private var frontQueue = LinkedList()
private var backQueue = LinkedList()
init() {
}
func push(_ x: Int) {
if frontQueue.size() > 0 {
backQueue.push(x)
while frontQueue.size() > 0 {
let val = frontQueue.popFront()
backQueue.push(val)
}
swapQueues()
}
else {
frontQueue.push(x)
}
}
func pop() -> Int {
let val = frontQueue.popFront()
return val
}
func top() -> Int {
return frontQueue.peak()
}
func empty() -> Bool {
return frontQueue.isEmpty()
}
private func swapQueues() {
let temp = frontQueue
frontQueue = backQueue
backQueue = temp
}
}
/**
* Your MyStack object will be instantiated and called as such:
* let obj = MyStack()
* obj.push(x)
* let ret_2: Int = obj.pop()
* let ret_3: Int = obj.top()
* let ret_4: Bool = obj.empty()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment