go: add «232. Implement Queue using Stacks»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-29 12:36:17 +01:00
parent 3f7519022a
commit 47c6862e92
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 105 additions and 0 deletions

View file

@ -0,0 +1,56 @@
package implement_queue_using_stacks
import (
"slices"
)
type MyQueue struct {
asQueue []int
asStack []int
}
func Constructor() MyQueue {
return MyQueue{
asQueue: make([]int, 0, 16),
asStack: make([]int, 0, 16),
}
}
func (this *MyQueue) Push(x int) {
this.asStack = append(this.asStack, x)
}
func (this *MyQueue) ReverseIfNeeded() {
if len(this.asQueue) > 0 {
return
}
slices.Reverse(this.asStack)
this.asQueue = this.asStack
this.asStack = make([]int, 0, 16)
}
func (this *MyQueue) Pop() int {
result := this.Peek()
this.asQueue = this.asQueue[:len(this.asQueue)-1]
return result
}
func (this *MyQueue) Peek() int {
this.ReverseIfNeeded()
return this.asQueue[len(this.asQueue)-1]
}
func (this *MyQueue) Empty() bool {
return len(this.asStack) == 0 && len(this.asQueue) == 0
}
/**
* Your MyQueue object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Peek();
* param_4 := obj.Empty();
*/

View file

@ -0,0 +1,49 @@
package implement_queue_using_stacks
import (
"testing"
)
func TestEmpty(t *testing.T) {
obj := Constructor()
if !obj.Empty() {
t.Error("Queue should be empty")
}
}
func TestBasic(t *testing.T) {
q := Constructor()
q.Push(1)
q.Push(2)
if q.Peek() != 1 {
t.Error("1 should be at the front of the queue")
}
if q.Pop() != 1 {
t.Error("1 should've been removed from the queue")
}
if q.Empty() {
t.Error("Queue shouldn't be empty")
}
q.Push(3)
if q.Pop() != 2 {
t.Error("Queue should've removed 2")
}
if q.Empty() {
t.Error("Queue shouldn't be empty")
}
if q.Pop() != 3 {
t.Error("Queue should've removed 3")
}
if !q.Empty() {
t.Error("Queue should be empty")
}
}