java 杨辉三角 循环队列_用循环队列实现打印杨辉三角(数据结构)

打印二项式系数表(即杨辉三角)

1

1 2 1

1 3 3 1

1 4 6 4 1

系数表中的第K行有k+1个数,除了第一个数和最后一个数为1外,其余的数则为上一行中位其左右的两数之和。

如果要求计算并输出杨辉三角前N行的值,则队列的最大空间应为n+2(第N行有n+1个数,且根据循环队列的特性:“少用一个元素”,但在这里少用的那个元素用来存放临界值“0”)。

#include"QueueSq.cpp"

void InitQueue(SqQueue &Q,int n)

{

Q.elem=new QElemType[n];

//为循环队列分配空间(比实际能用多一个元素)

Q.queuesize=n;

Q.incrementsize=QUEUEINCREMENT;

Q.top=Q.rear=0;

}

void YangHui(int n)

{

SqQueue Q;

int i,k;

for(i=1;i<=n;i++)

cout

//在利用顺序分配存储结构实现队列时,除了用一维数组描述队列中的数据元素的存储区域,需设立两个指针Top,rear

//指示队头和队尾的位置,为叙述方便,在此约定:初始化建立空队列时,另top=rear=0,每当插入一个元素后,尾指针rear+1,

//每当删除一个元素时top+1,头指针始终指向队头元素,而尾指针始终指向队尾元素的“下一个”位置。

#include#include#includeusing namespace std;

typedef int QElemType;

#define QUEUEINCREMENT 10

struct SqQueue

{

QElemType *elem;

int top;

int rear;

int queuesize;

int incrementsize;

};

#define QUEUE_INIT_SIZE 100

void InitQueue_Sq(SqQueue &Q)

{

Q.elem=new QElemType[QUEUE_INIT_SIZE+1];

//为循环队列分配空间(比实际能用多一个元素)

Q.queuesize=QUEUE_INIT_SIZE+1;

Q.incrementsize=QUEUEINCREMENT;

Q.top=Q.rear=0;

}

void EnQueue_Sq(SqQueue &Q,QElemType e)

{

//插入元素e为Q的新的队尾元素

if((Q.rear+1)%Q.queuesize==Q.top)//队满的判断

{

QElemType *a;

a=new QElemType [Q.queuesize+Q.incrementsize];

for(int k=0;k该算法的时间复杂度为O(n*n),因为外循环的次数为n-1,内循环的次数分别为3,4,5,............

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用C语言实现循环队列生成杨辉三角的代码: ```c #include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 // 定义循环队列 typedef struct { int front; // 队首指针 int rear; // 队尾指针 int items[MAX_SIZE]; // 队列元素 } Queue; // 初始化队列 void init_queue(Queue *q) { q->front = q->rear = 0; } // 判断队列是否为空 int is_empty(Queue *q) { return q->front == q->rear; } // 判断队列是否已满 int is_full(Queue *q) { return (q->rear + 1) % MAX_SIZE == q->front; } // 元素入队 void enqueue(Queue *q, int item) { if (!is_full(q)) { q->items[q->rear] = item; q->rear = (q->rear + 1) % MAX_SIZE; } } // 元素出队 int dequeue(Queue *q) { if (!is_empty(q)) { int item = q->items[q->front]; q->front = (q->front + 1) % MAX_SIZE; return item; } return -1; } // 生成杨辉三角 void generate_yanghui_triangle(int n) { Queue q; init_queue(&q); enqueue(&q, 1); // 第一行只有一个数字1 for (int i = 0; i < n; i++) { for (int j = 0; j <= i; j++) { printf("%d ", q.items[j]); } printf("\n"); for (int j = 0; j <= i; j++) { enqueue(&q, dequeue(&q) + q.items[j]); } enqueue(&q, 1); // 行末添加数字1 } } int main() { generate_yanghui_triangle(5); // 生成5行杨辉三角 return 0; } ``` 代码中定义了一个循环队列结构体Queue,包含front、rear和items三个成员变量。init_queue函数用于初始化队列,is_empty和is_full函数用于判断队列是否为空和已满,enqueue和dequeue函数实现元素的入队和出队操作。generate_yanghui_triangle函数使用队列来生成杨辉三角,通过两个for循环遍历队列中的数字并输出,将队首出队并加上队列中的每个数字,将结果入队,最后再将数字1入队。重复这个过程,就可以生成指定行数的杨辉三角
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值