C++抽象出链队,打印杨辉三角
#include <iostream>
using namespace std;
enum status {
success, failed
};
template<class T>
class node {
public:
T data;
node<T>* next;
};
template<class T>
class LinkedQueue {
public:
LinkedQueue() {
head = rear = new node<T>;
rear->next = nullptr;
count = 0;
}
bool isEmpty();
int getLength();
status enQueue(T x);
status deQueue(T& x);
status travQueue();
private:
node<T>* head;
node<T>* rear;
int count;
};
template<class T>
bool LinkedQueue<T>::isEmpty() {
return count == 0;
}
template<class T>
int LinkedQueue<T>::getLength() {
return count;
}
template<class T>
status LinkedQueue<T>::enQueue(T x) {
node<T>* cur = new node<T>;
if (cur) {
cur->data = x;
cur->next = nullptr;
rear->next = cur;
rear = cur;
count++;
return success;
}
else {
return failed;
}
}
template<class T>
status LinkedQueue<T>::deQueue(T& x) {
if (isEmpty()) {
return failed;
}
else {
node<T>* cur = head->next;
x = cur->data;
head->next = cur->next;
delete cur;
count--;
return success;
}
}
template<class T>
status LinkedQueue<T>::travQueue() {
if (head->next) {
node<T>* cur = head->next;
while (cur != nullptr) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
return success;
}
return failed;
}
void printSpaces(int n) {
for (int i = 0; i < n; i++) {
cout << " ";
}
}
void Yanghui(int n) {
LinkedQueue<int> queue;
printSpaces(n-1);
cout << 1 << endl;
int prev = 0;
int flag = 0;
int cur = 0;
queue.enQueue(1);
queue.enQueue(1);
for (int i = 1; i < n; i++)
{
printSpaces(n-1-i);
queue.enQueue(flag);
for (int j = 0; j <= i + 1; j++)//第i行i+1个数
{
queue.deQueue(cur);
queue.enQueue(prev + cur);
prev = cur;
if (j != i + 1)
{
cout << cur << " ";
}
}
cout << endl;
}
}
int main() {
cout << "请输入杨辉三角行数:";
int n; cin >> n;
Yanghui(n);
return 0;
}
复用STL版本:
#include<iostream>
#include<queue>
using namespace std;
void printSpaces(int n) {
for (int i = 0; i < n; i++) {
cout << " ";
}
}
void Yanghui(int n) {
queue<int> q;
printSpaces(n - 1);
cout << 1 << endl;
int prev = 0;
int flag = 0;
int cur = 0;
q.push(1);
q.push(1);
for (int i = 1; i < n; i++)
{
printSpaces(n - 1 - i);
q.push(flag);
for (int j = 0; j <= i + 1; j++)//第i行i+1个数
{
cur=q.front();
q.pop();
q.push(prev + cur);
prev = cur;
if (j != i + 1)
{
cout << cur << " ";
}
}
cout << endl;
}
}
int main() {
cout << "请输入杨辉三角行数:";
int n; cin >> n;
Yanghui(n);
return 0;
}