package main
import "fmt"
/*利用数组实现一个建议队列
实现尾部插入队列,头部删除队列
*/
type Queue interface {
Newqueue() (*Mqueue)
Size() int
IsEmpty() bool
Enqueue(string)
Dequeue() (interface{})
Clear()
}
type Mqueue struct{
dataStore []interface{}
dataSize int
}
func Newqueue() (*Mqueue){
myqueue := new(Mqueue)
myqueue.dataStore = make([]interface{},0)
myqueue.dataSize = 0
return myqueue
}
func (myq *Mqueue) Size() int{
return myq.dataSize
}
func (myq *Mqueue) IsEmpty() bool{
return myq.dataSize == 0
}
func (myq *Mqueue) Enqueue(s interface{}){
myq.dataStore = append(myq.dataStore,s)
myq.dataSize++
}
func (myq *Mqueue) Dequeue() (interface{}){
if myq.dataSize == 0{
return nil
}
backdata := myq.dataStore[0]
if myq.dataSize > 1 {
myq.dataStore = myq.dataStore[1 : myq.dataSize]
myq.dataSize--
return backdata
} else if myq.dataSize == 1{
myq.dataStore = make([]interface{},0)
myq.dataSize = 0
}
return backdata
}
func (myq *Mqueue) Clear(){
myq.dataStore = make([]interface{},0)
myq.dataSize = 0
}
func main(){
myqueue := Newqueue()
//压入数据到队列
myqueue.Enqueue(1)
myqueue.Enqueue("xiaotian")
//获取队列大小
fmt.Println(myqueue.Size())
//从队列弹出数据
fmt.Println(myqueue.Dequeue())
fmt.Println(myqueue.Dequeue())
//获取队列大小
fmt.Println(myqueue.Size())
}
输出结果如下截图
结果
网友评论