數據結構之楊輝三角(隊列實現)(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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM