顺序队列模板简单应用算法设计:杨辉三角形

 顺序队列模板简单应用算法设计:杨辉三角形

作者: 冯向阳时间限制: 1S章节: DS:队列

截止日期: 2022-06-30 23:55:00

问题描述 :

目的:使用C++模板设计顺序队列的抽象数据类型(ADT)。并在此基础上,使用顺序队列ADT的基本操作,设计并实现简单应用的算法设计。

内容:(1)请参照顺序栈的ADT模板,设计顺序队列的抽象数据类型。(由于该环境目前仅支持单文件的编译,故将所有内容都集中在一个源文件内。在实际的设计中,推荐将抽象类及对应的派生类分别放在单独的头文件中。参考教材、课件,以及网盘中的顺序栈ADT原型文件,自行设计顺序队列的ADT。)

(2)ADT的简单应用:使用该ADT设计并实现若干应用顺序队列的算法设计。

应用1:要求设计一个算法,使用顺序队列,设计并实现打印输出杨辉三角形前N行元素的算法。

参考函数原型:

template<class ElemType>

void YangHuiTriangle(SqQueue<ElemType> &Q, int N);

顺序队列的ADT原型如下所示:

const int MAXLISTSIZE = 100;

template<class ElemType>
class SqQueue{
   private:
      ElemType *elem;   // 存储空间基址
      int front;   // 队头指针
      int rear;   // 队尾指针
      int maxSize;        // 允许的最大存储容量(以sizeof(ElemType)为单位
   public:
      //初始化顺序队列
      SqQueue(int ms = 20);
      //删除顺序队列
      ~SqQueue(){QueueDestroy();}
      //将顺序队列置为空
      bool QueueClear( );
      //设置顺序栈的长度
      //bool SetListLength(int len);
      //判断顺序队列是否为空
      bool QueueisEmpty() const{ return front == rear; }
      //判断顺序队列是否为满
      bool QueueFull() const;
      //用e返回队头元素
      bool GetFront(ElemType &e);
      //入队
      bool enQueue(const ElemType &e);
      //出队
      bool deQueue(ElemType &e);
      //销毁顺序队列
      bool QueueDestroy(); 
      //顺序队列最大存储空间加倍
      bool DoubleSpace();
};

输入说明 :

第一行:杨辉三角形的行数

输出说明 :

杨辉三角形(左对齐)

输入范例 :

8

输出范例 :

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1


这个题之前在程序设计的题目里也出现过,这里用栈的标准库函数,也很方便~

AC代码:

#include<stdio.h>
#include<iostream>
#define MAX 1000
using namespace std;
struct SqQueue
{
    int sq[MAX];
    int front;
    int rear;
} SqQueue;

int initqueue()
{
    SqQueue.front = 0;
    SqQueue.rear = 0;
    return 0;
}
int enQueue(int q)
{
    SqQueue.sq[SqQueue.rear] = q;
    SqQueue.rear++;
    return 0;
}
bool QueueisEmpty()
{
    if (SqQueue.front == SqQueue.rear)
        return true;
    else
        return false;
}
int deQueue()
{
    if (QueueisEmpty())
        return -1;
    int v = SqQueue.sq[SqQueue.front];
    SqQueue.front++;
    return v;
}
int GetFront()
{
    return SqQueue.sq[SqQueue.front];
}
int main()
{
    int n;
    scanf("%d",&n);
    initqueue();
    enQueue(0);
    enQueue(1);
    printf("%d\n", 1);
    for (int i=1; i<n; i++)
    {
        enQueue(0);
        for (int j=0; j<=i; j++)
        {
            int q = deQueue();
            q += GetFront();
            enQueue(q);
            if(j!=i)
            printf("%d ",q);
            if(j==i)
                printf("%d",q);
        }
        printf("\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值