// 232.用栈实现队列
package main
import "fmt"
type MyQueue struct {
stackIn []int //输入栈
stackOut []int //输出栈
}
func Constructor() MyQueue {
return MyQueue{
stackIn: make([]int, 0),
stackOut: make([]int, 0),
}
}
// 往输入栈做push
func (this *MyQueue) Push(x int) {
this.stackIn = append(this.stackIn, x)
}
//如果输入栈为空,返回-1,否则往输出栈做pop,如果输出栈为空,则把输入栈所有元素逆序放在输入栈中
func (this *MyQueue) Pop() int {
inLen, outLen := len(this.stackIn), len(this.stackOut)
if outLen == 0 {
if inLen == 0 { //如果输入栈为空,返回-1
return -1
}
for i := inLen - 1; i >= 0; i-- { //注意这里是>=0
this.stackOut = append(this.stackOut, this.stackIn[i])
}
this.stackIn = make([]int, 0) //导出后清空输入栈
outLen = len(this.stackOut) //更新输出栈
}
val := this.stackOut[outLen-1] //最后一个元素出栈
this.stackOut = this.stackOut[:outLen-1] //删除最后一个元素
return val
}
//获取队列的第一个元素
func (this *MyQueue) Peek() int {
head := this.Pop() //出栈
this.stackOut = append(this.stackOut, head) //再加入栈保证输出栈的完整性
return head
}
//如果队列为空,返回 true ;否则,返回 false
func (this *MyQueue) Empty() bool {
return len(this.stackIn) == 0 && len(this.stackOut) == 0
}
func main() {
q := Constructor()
q.Push(1)
q.Push(2)
q.Push(3)
fmt.Printf("q: %v\n", q) //q: {[1 2 3] []}
fmt.Printf("q.Pop(): %v\n", q.Pop()) //q.Pop(): 1
fmt.Printf("q: %v\n", q) //q: {[] [3 2]}
fmt.Printf("q.Peek(): %v\n", q.Peek()) //q.Peek(): 2
fmt.Printf("q: %v\n", q) //q: {[] [3 2]}
fmt.Printf("q.Empty(): %v\n", q.Empty()) //q.Empty(): false
}
// 225.用队列实现栈
package main
import "fmt"
type MyStack struct {
queue []int
}
func Constructor() MyStack {
return MyStack{queue: make([]int, 0)}
}
func (this *MyStack) Push(x int) {
this.queue = append(this.queue, x)
}
func (this *MyStack) Pop() int {
length := len(this.queue)
if length == 0 { //判断是否有非法操作
return -1
}
for i := 0; i < length-1; i++ { //将最后一个元素前面的元素先出队列再入队列
this.queue = append(this.queue, this.queue[0])
this.queue = this.queue[1:]
}
val := this.queue[0] //取出出队列元素
this.queue = this.queue[1:] //删除该元素
return val
}
//取出口的第一个元素
func (this *MyStack) Top() int {
length := len(this.queue)
return this.queue[length-1]
}
//判读队列是否为空
func (this *MyStack) Empty() bool {
return len(this.queue) == 0
}
func main() {
q := Constructor()
q.Push(1)
q.Push(2)
q.Push(3)
q.Push(4)
fmt.Printf("q: %v\n", q) //q: {[1 2 3 4]}
fmt.Printf("q.Pop(): %v\n", q.Pop()) //q.Pop(): 4
fmt.Printf("q.Pop(): %v\n", q.Pop()) //q.Pop(): 3
fmt.Printf("q.Top(): %v\n", q.Top()) //q.Top(): 2
fmt.Printf("q: %v\n", q) //q: {[1 2]}
fmt.Printf("q.Empty(): %v\n", q.Empty()) //q.Empty(): false
}