用队列实现杨辉三角

 

1,队列是一种特殊的线性表,具有先进先出的特点,采用循环队列主要    提高空间利用率

2,其两端队头队尾都可以进行数据操作

3,空队 : 对头队尾相等   front = rear

     队满  : (rear + 1) % SIZE  == front

   队长度判断  (rear - front + SIZE) % SIZE 

队常用操作

创建队   

进队出队

获取队首元素

清空队

获取队列长度

头文件

#ifndef _SEQUENCEQUEUE_H
#define _SEQUENCEQUEUE_H

#define SIZE  30

#define FAILURE  10000
#define SUCCESS  10001
#define FALSE    10002
#define TRUE     10003

struct queue
{
    int data[SIZE];
    int front;
    int rear;
};

typedef struct queue Queue;

int QueueInit(Queue *q);
int QueueEmpty(Queue q);
int QueueEnter(Queue *q, int i);
int QueueExit(Queue *q);
int QueueGet(Queue *q);
int QueueLength(Queue *q);
int QueueClear(Queue *q);

#endif
#include <stdio.h>
#include "SequenceQueue.h"

int QueueInit(Queue *q)
{
    if(NULL == q)
    {
        return FAILURE;
    }
    q->front = q->rear = 0;
    return SUCCESS;
}

int QueueEmpty(Queue q)
{
    return (q.front == q.rear) ? TRUE : FALSE;
}

int QueueEnter(Queue *q, int e)
{
    if(NULL == q)
    {
        return FAILURE;
    }
    if(((q->rear + 1) % SIZE) == q->front)
    {
        return FAILURE;
    }
    q->data[q->rear] = e;
    q->rear = (q->rear + 1) % SIZE;
    return SUCCESS;
}

int QueueExit(Queue *q)
{
    if(NULL == q)
    {
        return FAILURE;
    }
    if(q->front == q->rear)
    {
        return FAILURE;
    }
    int e = q->data[q->front];
    q->front = (q->front + 1) % SIZE;
    return e;
}

int QueueGet(Queue *q)
{
    if(NULL == q)
    {
        return FAILURE;
    }
    return q->data[q->front];
}

int QueueLength(Queue *q)
{
    if(NULL == q)
    {
        return FAILURE;
    }

    return (q->rear - q->front + SIZE) % SIZE;
}

int QueueClear(Queue *q)
{
    if(NULL == q)
    {
        return FAILURE;
    }
    q->front = q->rear;

    return SUCCESS;
}
#include <stdio.h>
#include "SequenceQueue.h"

int main()
{
    Queue q1, q2;
    int i, j;

    if(QueueInit(&q1) != SUCCESS || QueueInit(&q2) != SUCCESS)
    {
        printf("Init FAILURE!\n");
    }

    QueueEnter(&q1, 0);
    QueueEnter(&q1, 1);
    QueueEnter(&q1, 0);
    //printf("%d %d %d\n", QueueGet(&q1), QueueGet(&q1), QueueGet(&q1));

    for(i = 2; i < 12; i++)
    {
        QueueEnter(&q2, 0);
        for(j = 0; j < i; j++)
        {
            QueueEnter(&q1, QueueExit(&q2));
            QueueEnter(&q2, (QueueExit(&q1) + QueueGet(&q1)));
            printf("%d ",QueueGet(&q2));
        }
        printf("\n");
        QueueExit(&q1);
        QueueEnter(&q1, QueueExit(&q2));
        QueueEnter(&q1, 0);
    }
    return 0;
}

PS:头文件中一开始设置了队列的容量为10, 所以显示杨辉三角列数 到第九行就出现问题  ,想半天还以为是程序没写好,但其实是队列容量为10,但其实最多只能容纳九个数据

猜你喜欢

转载自blog.csdn.net/weixin_42720316/article/details/81515290