day9 | 栈与队列 part-1 (Go) | 232 用栈实现队列、225 用队列实现栈
warning:
这篇文章距离上次修改已过205天,其中的内容可能已经有所变动。
在Go语言中,可以使用内置的数据结构[]interface{}
来实现栈和队列。以下是用Go实现的用栈实现队列和用队列实现栈的代码示例。
用栈实现队列:
type MyQueue struct {
stackIn []interface{}
stackOut []interface{}
}
func Constructor() MyQueue {
return MyQueue{
stackIn: make([]interface{}, 0),
stackOut: make([]interface{}, 0),
}
}
func (q *MyQueue) Push(x interface{}) {
q.stackIn = append(q.stackIn, x)
}
func (q *MyQueue) Pop() interface{} {
if len(q.stackOut) == 0 {
for len(q.stackIn) > 0 {
// 将stackIn中的元素转移到stackOut
q.stackOut = append(q.stackOut, q.stackIn[len(q.stackIn)-1])
q.stackIn = q.stackIn[:len(q.stackIn)-1]
}
}
if len(q.stackOut) == 0 {
return -1 // 队列为空
}
// 将stackOut的最后一个元素移到stackIn,并返回
x := q.stackOut[len(q.stackOut)-1]
q.stackOut = q.stackOut[:len(q.stackOut)-1]
return x
}
func (q *MyQueue) Peek() interface{} {
if len(q.stackOut) == 0 {
for len(q.stackIn) > 0 {
q.stackOut = append(q.stackOut, q.stackIn[len(q.stackIn)-1])
q.stackIn = q.stackIn[:len(q.stackIn)-1]
}
}
if len(q.stackOut) == 0 {
return -1 // 队列为空
}
return q.stackOut[len(q.stackOut)-1]
}
func (q *MyQueue) Empty() bool {
return len(q.stackIn) == 0 && len(q.stackOut) == 0
}
用队列实现栈:
type MyStack struct {
queueIn []interface{}
queueOut []interface{}
}
func Constructor() MyStack {
return MyStack{
queueIn: make([]interface{}, 0),
queueOut: make([]interface{}, 0),
}
}
func (s *MyStack) Push(x interface{}) {
s.queueIn = append(s.queueIn, x)
}
func (s *MyStack) Pop() interface{} {
if len(s.queueOut) == 0 {
for len(s.queueIn) > 1 {
// 将queueIn中的元素转移到queueOut,除了最后一个
s.queueOut = append(s.queueOut, s.queueIn[len(s.queueIn)-1])
s.queueIn = s.queueIn[:len(s.queueIn)-1]
}
// 最后一个元素从queueIn移动到queueOut,并返回
x := s.queueIn[0]
s.queueOut = append(s.queueOut, s.queueIn[0])
s.queueIn = s.queueIn[:0]
return x
}
// 如果queueOut不为空,直接从queueOut弹出元素
x := s.queueOut[len(s.queueOut)-1]
s.queueOut = s.queueOut[:len(s.queueOut)-1]
return x
}
func (s *MyStack) Top() interface{} {
if len(s.queueOut) == 0 {
for len(s.queueIn) > 1 {
s.queueOut = append(s.queueOut, s.queueIn[
评论已关闭