1. 编写类 queue ,实现简单的栈(FILO,先进后出)
用于存放整型变量
成员变量包括:
头节点
成员函数包括:
void push(int item); //将整型 item 压入栈中
int pop(); //从栈中弹出一个数据
int count(); //统计当前栈中的数据个数
bool empty(); //判断栈是否为空
#include<iostream>
#include<stdlib.h>
#include<windows.h>
using namespace std;
template<class T>class queue
{
private:
struct Node
{
T data;
Node* next;
};
Node* head;
Node* p;
public:
int length;
queue()
{
head = NULL;
length = 0;
}
void push(T n)//入栈
{
Node* q = new Node;
q->data = n;
if (head == NULL)
{
q->next = head;
head = q;
p = q;
}
else
{
q->next = p;
p = q;
}
length++;
}
T pop()//出栈并且将出栈的元素返回
{
if (length <= 0)
{
abort();
}
Node* q;
T data;
q = p;
data = p->data;
p = p->next;
delete(q);
length--;
return data;
}
void count()//返回元素个数
{
cout << length;
}
bool isEmpty()//判断栈是不是空的
{
if (length == 0)
{
return true;
}
else
{
return false;
}
}
void clear()//清空栈中的所有元素
{
while (length > 0)
{
pop();
}
}
};
int main()
{
queue<char> q;
q.push('a');
q.push('b');
q.push('c');
cout << "栈的元素有:" ;
q.count(); cout << endl;
cout << "出栈元素分别为:" << endl;
while (!q.isEmpty())
{
cout << q.pop() << endl;
}
return 0;
}