数据结构之python实现循环顺序队列实例

题目如下:

python实现:

class CircularSequenceQueue():
    def __init__(self):
        self.MaxQueueSize = 10
        self.s = [None for x in range(0,self.MaxQueueSize)]
        self.front = 0
        self.rear = 0
    '''当前队列是否为空'''
    def IsEmptyQueue(self):
        if self.front == self.rear:
            iQueue = True
        else:
            iQueue = False  
        return iQueue
    '''获取队头元素'''
    def  GetHead(self):
        if self.IsEmptyQueue():
            print("队列为空")
            return
        else:
            return self.s[self.front+1]
    def GetQueueLength(self):
        return (self.rear - self.front+self.MaxQueueSize) % self.MaxQueueSize
    '''元素进队'''
    def EnQueue(self,x):
        if (self.rear+1)% self.MaxQueueSize != self.front:
            self.rear = (self.rear+1)% self.MaxQueueSize
            self.s[self.rear] = x
            print("当前进队元素为:",x)
        else:
            print("队列已满")
            return
    '''元素出队'''   
    def DeQueue(self):
        if self.IsEmptyQueue():
            print("队列为空")
        else:
            self.front = (self.front+1)% self.MaxQueueSize
            return self.s[self.front]
class TestFN():
    def Fibonacci(self,n):
        qu =  CircularSequenceQueue()
        if n == 0:
            print("起始兔子的总对数为: 1")
            return
        elif n == 1:
            print("第 1 个月兔子的总对数为: 2")
            return
        else:
            qu.EnQueue(1)
            qu.EnQueue(2)   
            mounth = 1
        while mounth < n:
            NumHead = qu.DeQueue()
            NumRear = qu.GetHead()
            qu.EnQueue(NumHead + NumRear)
            mounth = mounth+1
        qu.DeQueue()
        print("第",n,"个月兔子的总对数为: ",qu.DeQueue())
num = int(input("请输入月份:"))
TEN = TestFN()
TEN.Fibonacci(num)

结果如下:
数据结构之python实现循环顺序队列实例_第1张图片

你可能感兴趣的:(python数据结构,循环顺序队列)