Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created March 27, 2020 09:36
Show Gist options
  • Select an option

  • Save alldroll/e5605c5c8f9b9f755c9716c62424c189 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/e5605c5c8f9b9f755c9716c62424c189 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/implement-queue-using-stacks
// -> [][][][] ->
// <-> [][][][]
// <-> [][][][]
type MyQueue struct {
front int
ordered []int
reversed []int
}
/** Initialize your data structure here. */
func Constructor() MyQueue {
return MyQueue{
front: 0,
ordered: []int{},
reversed: []int{},
}
}
/** Push element x to the back of queue. */
func (q *MyQueue) Push(x int) {
q.ordered = append(q.ordered, x)
if len(q.ordered) == 1 {
q.front = x
}
}
/** Removes the element from in front of queue and returns that element. */
func (q *MyQueue) Pop() int {
if len(q.reversed) == 0 {
for _, x := range q.ordered {
q.reversed = append(q.reversed, x)
}
q.ordered = q.ordered[:0]
}
top := q.reversed[0]
q.reversed = q.reversed[1:]
return top
}
/** Get the front element. */
func (q *MyQueue) Peek() int {
if len(q.reversed) > 0 {
return q.reversed[0]
}
return q.front
}
/** Returns whether the queue is empty. */
func (q *MyQueue) Empty() bool {
return len(q.ordered) == 0 && len(q.reversed) == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment