用户输入n个元素,由程序给出它的倒序输出。
程序直接包含头文件<stack>,该程序将numbers设置为栈类型,并调用了stack.push(),stack.top(),stack.pop()函数;
#include<stack>
#include<iostream>
using namespace std;
int main(){
int n;
double item;
stack<double> numbers;
cout << "Type in an integer n followed by n demical numbers." << endl<< "The numbers will be printed in reverse order." << endl;
cin >> n;
for(int i = 0; i < n; i++){
cin >> item;
numbers.push(item);
}
cout << endl;
while (!numbers.empty()){
cout << numbers.top() << " ";
numbers.pop();
}
cout << endl;
}
程序输出如下:
栈的实现:
以数组的形式实现,其中包含构造函数,push()函数,pop()函数,empty()函数,top()函数,还有print()函数;
#include <iostream>
#define MAXSIZE 10
using namespace std;
enum Error_code{
success, overflow, underflow
};
typedef char Stack_entry;
class Stack{
private:
int count;
Stack_entry Entry[MAXSIZE];
public:
//构造函数
Stack(){
count = 0;
}
//检验函数是否为空
bool empty() const{
if(count == 0) return true;
else return false;
}
//入栈函数
Error_code push(const Stack_entry & item){
Error_code outcome = success;
if (count == (MAXSIZE - 1))
outcome = overflow;
else{
Entry[count] = item;
count++;
}
return outcome;
}
//出栈函数
Error_code pop(){
Error_code outcome = success;
if(count == 0)
outcome = underflow;
else{
count--;
}
return outcome;
}
//获得最外面的元素(不对栈产生任何影响)
Error_code top(Stack_entry & item) const{
Error_code outcome = success;
if(count == 0)
outcome = underflow;
else
item = Entry[count-1];
return outcome;
}
//打印栈的元素
void print(){
for(int i = 0;i < count;i++){
cout << Entry[i] << " ";
}
}
};
扩展的栈数据结构的顺序实现:
与栈相比,多了full()函数,clear()函数,以及size()函数
因为其他的函数实现与栈相同,这里不再重复
clear(){
count = 0;
}
//检验函数是不是满
bool full() const{
if(count >= MAXSIZE) return true;
return false;
}
//计算栈的元素个数
int size() const{
return count;
}