Skip to content

Instantly share code, notes, and snippets.

@derekli66
Created May 13, 2022 21:04
Show Gist options
  • Save derekli66/0de5bf2dbf5ae1c056d718d5fe113377 to your computer and use it in GitHub Desktop.
Save derekli66/0de5bf2dbf5ae1c056d718d5fe113377 to your computer and use it in GitHub Desktop.
Solution to LeetCode problem, 232 Implement Queue using Stacks. https://leetcode.com/problems/implement-queue-using-stacks/
private class ListNode {
var next: ListNode?
var prev: ListNode?
var key: Int = 0
}
class Stack {
private var head: ListNode?
private var tail: ListNode?
private var count: Int = 0
func push(_ key: Int) {
let newNode = ListNode()
newNode.key = key
if tail == nil {
tail = newNode
head = newNode
}
else {
newNode.next = head
head = newNode
}
count += 1
}
func pop() -> Int {
let lastNode = head
head = lastNode?.next
if head == nil {
tail = nil
}
count -= 1
return lastNode?.key ?? 0
}
func peak() -> Int {
return head?.key ?? 0
}
func size() -> Int {
return count
}
func isEmpty() -> Bool {
return size() == 0
}
}
class MyQueue {
private var frontStack = Stack()
private var backStack = Stack()
private var count = 0
init() {
}
func push(_ x: Int) {
frontStack.push(x)
count += 1
}
func pop() -> Int {
if backStack.size() > 0 {
count -= 1
return backStack.pop()
}
else {
while frontStack.size() > 0 {
backStack.push(frontStack.pop())
}
if backStack.size() > 0 {
count -= 1
return backStack.pop()
}
return 0
}
}
func peek() -> Int {
if backStack.size() > 0 {
return backStack.peak()
}
else {
while frontStack.size() > 0 {
backStack.push(frontStack.pop())
}
if backStack.size() > 0 {
return backStack.peak()
}
}
return 0
}
func empty() -> Bool {
return count == 0
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* let obj = MyQueue()
* obj.push(x)
* let ret_2: Int = obj.pop()
* let ret_3: Int = obj.peek()
* let ret_4: Bool = obj.empty()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment