开始学go了,之前为了面试搞得数据结构都忘了,mmp,虽然当时也是脸懵逼。 而且现在写python的类,居然有些卡壳,,阿哲。
总的意思就是,给数据多预留一个位置。
判断条件: full: (head + 1) % max_size == head 从图看,判断满了及时tail 在head 后面紧挨着
empty: tail == head
size(队列长度): (tail - head + max_size) % max_size 就是tail - head 但是为了消除循环的影响,才这么搞
package main
import (
"errors"
"fmt"
"os"
)
type CircleQueue struct {
maxSize int
array [5]int
head int
tail int
}
func (this *CircleQueue) Push (val int) (err error){
if this.IsFull() {
return errors.New("已经满了")
}
fmt.Println("加入", val)
this.array[this.tail % this.maxSize] = val
this.tail ++
return
}
func (this *CircleQueue) Pop() (val int, err error) {
if this.IsEmpty() {
return 0, errors.New("为空")
}
val = this.array[this.head % this.maxSize]
this.head ++
return
}
// IsFull 队列shi不是满了
func (this *CircleQueue) IsFull() bool{
return (this.tail + 1) % this.maxSize == this.head
}
func (this *CircleQueue) IsEmpty() bool {
return this.tail == this.head
}
func (this *CircleQueue) Size() int {
return (this.tail + this.maxSize - this.head) % this.maxSize
}
func (this *CircleQueue) ListQueue() {
size := this.Size()
if size == 0{
fmt.Println("为空")
}
temHEead := this.head
for i:=0;i < size; i++ {
fmt.Printf("arr[%d]=%d\n", temHEead, this.array[temHEead])
temHEead = (temHEead + 1) % this.maxSize
}
}
func main() {
queue := &CircleQueue{
maxSize: 5,
head: 0,
tail: 0,
}
var key string
var val int
for {
fmt.Println("add")
fmt.Println("get")
fmt.Println("show")
fmt.Println("exit")
fmt.Scanln(&key)
switch key {
case "add":
fmt.Println("添加")
fmt.Scanln(&val)
err := queue.Push(val)
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("加入成功")
}
case "get":
val, err := queue.Pop()
if err != nil{
fmt.Println(err.Error())
}else {
fmt.Println("取出一个数", val)
}
case "show":
queue.ListQueue()
case "exit":
os.Exit(0)
}
}
}
python:
class Queue:
def __init__(self):
self.head = 0
self.tail = 0
self.size = 5
self.queue = [None for i in range(self.size)]
def push(self, val):
if self.is_full():
print("队列已经满了")
return "队列已经满了"
self.queue[self.tail % self.size] = val
self.tail += 1
print(f"添加{val}成功")
def pop(self):
if self.if_empty():
print("队列为空")
return "队列为空"
val = self.queue[self.head % self.size]
print("取出的值为", val)
self.head += 1
def is_full(self):
return (self.tail + 1) % self.size == self.head
def if_empty(self):
return self.head == self.tail
def queue_len(self):
return (self.tail + self.size - self.head) % self.size
def show_queue(self):
tem = self.head
result = []
for i in range(self.queue_len()):
result.append(self.queue[tem])
tem = (tem + 1) % self.size
print(result)
q = Queue()
q.push(1)
q.push(2)
q.push(3)
q.show_queue()
q.push(4)
q.push(5)
q.show_queue()
q.pop()
q.show_queue()
q.pop()
q.show_queue()
q.push(5)
q.push(6)
q.show_queue()
q.push(8)
q.pop()