Created
March 27, 2020 09:36
-
-
Save alldroll/e5605c5c8f9b9f755c9716c62424c189 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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