zoukankan      html  css  js  c++  java
  • 数据结构之杨辉三角(队列实现)(C++版)

    #include <iostream>
    #include <stdlib.h>
    #include <windows.h>
    #include <string>
    #define MAXLISTSIZE 100 //预设的存储空间最大容量
    #define TRUE 1
    #define FALSE 0
    using namespace std;
    typedef int ElemType;
    typedef struct
    {
    ElemType *elem; //存储空间基址   
    int rear; //队尾指针   
    int front; //队头指针
    int queuesize; //允许的最大存储空间,以元素为单位  
    }Queue;

    void InitQueue(Queue &Q, int maxsize)
    {
    //构造一个最大存储空间为 maxsize 的空队列 Q  
    if (maxsize == 0)
    maxsize = MAXLISTSIZE;
    Q.elem = new ElemType[maxsize]; //为循环队列分配存储空间  
    if (!Q.elem) exit(1); //存储分配失败
    Q.queuesize = maxsize;
    Q.front = Q.rear = 0;
    } //InitQueue

    bool EnQueue(Queue &Q, ElemType e)
    {
    // 若当前队列不满,这在当前队列的尾元素之后,插入元素 e 为新的队列尾元素,并返回TRUE,否则返回FALSE
    if((Q.rear + 1) % Q.queuesize == Q.front)
    return FALSE;
    Q.elem[Q.rear] = e;
    Q.rear = (Q.rear+1) % Q.queuesize;
    return TRUE;
    }

    bool DeQueue(Queue &Q, ElemType &e)
    {
    //若队列不空,则删除当前队列Q中的头元素,用 e 返回其值,并返回TRUE,否则返回 FALSE 
    if (Q.front == Q.rear)
    return FALSE;
    e = Q.elem[Q.front];
    Q.front = (Q.front+1) % Q.queuesize;
    return TRUE;
    }

    bool GetHead(Queue Q, ElemType &e)
    {
    //若队列不空,则用 e 返回队首元素,并返回TRUE,否则返回 FALSE
    if (Q.front == Q.rear)
    return FALSE;
    e = Q.elem[Q.front];
    return TRUE;
    }

    int QueueLength(Queue Q)
    {
    //返回队列Q中元素个数,即队列的长度
    return((Q.rear-Q.front+Q.queuesize) % Q.queuesize);
    }

    bool QueueEmpty(Queue Q)
    {
    if(Q.front == Q.rear)
    return TRUE;
    else
    return FALSE;
    }


    int main(void)
    {
    //打印输出杨辉三角的前n(n>0)行
    int n, i, k;
    Queue Q;
    ElemType s, e;
    cout << "请输入杨辉三角的行数:";
    cin >> n;
    /* for(i = 1; i <= n; i++)
    cout << ' ';
    cout<< '1' << endl; // 在中心位置输出杨辉三角最顶端的"1"*/
    InitQueue(Q, n+3); // 设置最大容量为 n+3 的空队列
    EnQueue(Q, 0); // 添加行界值
    EnQueue(Q, 1);
    EnQueue(Q, 1); // 第一行的值入队列
    k = 1;
    while(k < n)
    { // 通过循环队列输出前 n-1 行的值
    for(i = 1; i <= n - k; i++)
    cout<< ' '; // 输出n-k个空格以保持三角型
    EnQueue(Q, 0); // 行界值"0"入队列
    do { // 输出第 k 行,计算第 k+1 行
    DeQueue(Q, s);
    GetHead(Q, e);
    if(e) cout<< e << ' '; //若e为非行界值0,则打印输出 e 的值并加一空格
    else cout << endl; //否则回车换行,为下一行输出做准备
    EnQueue(Q, s+e);
    }while(e!=0);
    k++;
    }//while
    DeQueue(Q, e); //行界值"0"出队列
    while (!QueueEmpty(Q))
    { //单独处理第 n 行的值的输出
    DeQueue (Q, e);
    cout << e << ' ';
    }//while
    cout << endl;
    }//yanghui

  • 相关阅读:
    hdu 1017 A Mathematical Curiosity 解题报告
    hdu 2069 Coin Change 解题报告
    hut 1574 组合问题 解题报告
    hdu 2111 Saving HDU 解题报
    hut 1054 Jesse's Code 解题报告
    hdu1131 Count the Trees解题报告
    hdu 2159 FATE 解题报告
    hdu 1879 继续畅通工程 解题报告
    oracle的系统和对象权限
    oracle 自定义函数 返回一个表类型
  • 原文地址:https://www.cnblogs.com/wwttsqt/p/7783218.html
Copyright © 2011-2022 走看看