用循环队列输出杨辉三角形前7列
时间: 2024-05-03 15:22:12 浏览: 97
杨辉三角形可以用循环队列来计算,以下是输出前7列的代码:
```
#include <iostream>
using namespace std;
const int MAXSIZE = 100;
class Queue {
private:
int data[MAXSIZE];
int front, rear;
public:
Queue() {
front = rear = 0;
}
bool isEmpty() {
return front == rear;
}
bool isFull() {
return (rear + 1) % MAXSIZE == front;
}
void enqueue(int x) {
if (isFull()) {
cout << "Queue is full." << endl;
return;
}
data[rear] = x;
rear = (rear + 1) % MAXSIZE;
}
int dequeue() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return -1;
}
int x = data[front];
front = (front + 1) % MAXSIZE;
return x;
}
};
int main() {
Queue q;
q.enqueue(1);
for (int i = 1; i <= 7; i++) {
int prev = 0;
for (int j = 0; j < i; j++) {
int curr = q.dequeue();
q.enqueue(curr + prev);
cout << curr << " ";
prev = curr;
}
q.enqueue(1);
cout << endl;
}
return 0;
}
```
输出结果为:
```
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
```
阅读全文