顺序队列:
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<string>
using namespace std;
enum myerror_code { success, underflow, overflow };
//进5-2+3-1
//+5-2+3-7
template<class T>
struct node
{
T data;
node* next;
};
template<class T>
class queue
{
public:
int count;
node<T>* front;
node<T>* rear;
queue()
{
count = 0;
front = new node<T>;
front->next = NULL;
rear = front;
}
~queue()
{
while (!empty())
{
serve();
delete front;
}
}
bool empty()const
{
if (count == 0)
return true;
else
return false;
}
myerror_code getfront(T& x)
{
if (empty())
return underflow;
else
x = front->next->data;
return success;
}
myerror_code append(T x)
{
node<T>* s = new node<T>;
s->data = x;
s->next = NULL;
rear->next = s;
rear = s;
count++;
return success;
}
myerror_code serve()
{
if (empty())
return underflow;
node<T>* s = new node<T>;
s = front->next;
front->next = s->next;
delete s;
count--;
if (front->next == NULL) //这里特别注意删除最后一个节点的情况,当删除最后一个节点后,rear不可以丢失,应该让它再回归于front,回到最初的状态
rear = front;
return success;
}
};
int main()
{
int n = 0;
cout << "请输入需要打印的杨辉三角形的行数" << endl;
cin >> n;
int s1;
int s2;
queue<int> q;
cout << "1" << endl;
q.append(1);
for (int i = 2; i <= n; i++)
{
s1 = 0;
for (int j = 1; j <= i - 1; j++)
{
q.getfront(s2);
q.serve();
cout << s1 + s2 << " ";
q.append(s1 + s2);
s1 = s2;
}
cout << 1 << endl;
q.append(1);
}
}
链队列:
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<string>
using namespace std;
enum myerror_code { success, underflow, overflow };
//进5-2+3-1
//+5-2+3-7
template<class T>
struct node
{
T data;
node* next;
};
template<class T>
class queue
{
public:
int count;
node<T>* front;
node<T>* rear;
queue()
{
count = 0;
front = new node<T>;
front->next = NULL;
rear = front;
}
~queue()
{
while (!empty())
{
serve();
delete front;
}
}
bool empty()const
{
if (count == 0)
return true;
else
return false;
}
myerror_code getfront(T& x)
{
if (empty())
return underflow;
else
x = front->next->data;
return success;
}
myerror_code append(T x)
{
node<T>* s = new node<T>;
s->data = x;
s->next = NULL;
rear->next = s;
rear = s;
count++;
return success;
}
myerror_code serve()
{
if (empty())
return underflow;
node<T>* s = new node<T>;
s = front->next;
front->next = s->next;
delete s;
count--;
if (front->next == NULL) //这里特别注意删除最后一个节点的情况,当删除最后一个节点后,rear不可以丢失,应该让它再回归于front,回到最初的状态
rear = front;
return success;
}
};
int main()
{
int n = 0;
cout << "请输入需要打印的杨辉三角形的行数" << endl;
cin >> n;
int s1;
int s2;
queue<int> q;
cout << "1" << endl;
q.append(1);
for (int i = 2; i <= n; i++)
{
s1 = 0;
for (int j = 1; j <= i - 1; j++)
{
q.getfront(s2);
q.serve();
cout << s1 + s2 << " ";
q.append(s1 + s2);
s1 = s2;
}
cout << 1 << endl;
q.append(1);
}
}