标题:如何利用队列写出杨辉三角的算法?
只看楼主
ec_月月
Rank: 1
等 级:新手上路
帖 子:10
专家分:0
注 册:2008-10-8
得分:0 
用队列可以节省一半的空间,队列的空间复杂度就要低了
这是我写的队列杨辉三角,是金字塔状的。供大家参考。
#include<iostream.h>
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<process.h>

#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -2
#define MAXSIZE 100;

typedef int Status;
typedef int Boolean;
typedef int Qelemtype;

typedef struct{
    Qelemtype *base;
    int front;
    int rear;
}SqQueue;

Status InitQueue(SqQueue &Q)
{
    Q.base = (Qelemtype *)malloc(100*sizeof(Qelemtype));
    if(!Q.base) exit(ERROR);
    Q.front = Q.rear = 0;
    return OK;
}

Status EnQueue(SqQueue &Q,Qelemtype e)
{
    if( (Q.rear+1)%100 == Q.front )
        return ERROR;
    Q.base[Q.rear] = e;
    Q.rear = (Q.rear+1)%MAXSIZE;
    return OK;
}

Status DeQueue(SqQueue &Q,Qelemtype &e)
{
    if(Q.front == Q.rear)
        return ERROR;
    e = Q.base[Q.front];
    Q.front = (Q.front+1)%MAXSIZE;
    return OK;
}

Status GetHead(SqQueue &Q, Qelemtype &x)
{
    if(Q.front == Q.rear)
        return ERROR;
    x = Q.base[Q.front];
    return OK;
}

void YHTriangle()
{
    SqQueue Q;
    Qelemtype e,x;
    int i,j,n;
    InitQueue(Q);
       EnQueue(Q,1);
       cout<<"Please enter the value of n:";
       cin>>n;
       for(i=1;i<=n;++i)
       {
           EnQueue(Q,1);
           cout<<endl;
          for(j=1;j<=i-1;++j)
          {
            DeQueue(Q,e);
            cout<<e<<' ';
            GetHead(Q,x);
            e=e+x;
            EnQueue(Q,e);
          }
        DeQueue(Q,x);
        cout<<x<<' ';
        EnQueue(Q,1);
       }
}

void main()
{
    char a;
    do{
        YHTriangle();
        cout<<endl;
        cout<<"Do you want to do it again?(y/n)";
        cin>>a;
        if( a!='y'&&a!='n')
            cout<<"\a\a\a"<<"Please enter right and enter again!"<<endl;
    }while( (a=='y')&&(a!='n') );
}
2008-11-01 14:40
biaoxiaoqun
Rank: 1
等 级:新手上路
帖 子:4
专家分:0
注 册:2009-11-9
得分:0 
太长
2009-11-09 17:31
朱头健
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2011-9-29
得分:0 
感谢分享
2011-10-28 21:54



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-237967-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.023541 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved