#ifndef __STACK__H__
#define __STACK__H__
#include<iostream>
#include <vector>
using namespace std;
template <typename Object>
class stack
{
public:
stack(int size=-1):top(size){}
~stack(){};
int push(const Object &obj)
{
vec.push_back(obj);
top++;
return top;
}
Object pop()
{
Object tmp;
if (empty())
{
cout << "stack is empty" <<endl;
exit(-1);
}
tmp = vec[top];
vec.pop_back();
top--;
return tmp;
}
Object TopOut()
{
if (empty())
{
cout << "stack is empty" <<endl;
exit(-1);
}
return vec[top];
}
bool empty() const
{
return (top == -1);
}
private:
vector <Object> vec;
int top;
};
#endif
cpp:
//平衡符号
#include "stack.h"
int main(int argc,char *argv[])
{
char wgw[] = "{[]]";
stack <char>st;
int i = 0;
char tmp;
while (wgw[i] != '/0')
{
switch(wgw[i])
{
case '{':
st.push('{');
break;
case '}':
tmp = st.pop();
if (tmp != '{')
{
cout << "error: except:{,but:"<<tmp <<endl;
}
break;
case '[':
st.push('[');
break;
case ']':
tmp = st.pop();
if (tmp != '[')
{
cout << "error: except:[,but:"<<tmp <<endl;
}
break;
default:
cout << "error char"<<endl;
break;
}
i++;
}
return 0;
}
// 逆波兰式
int main(int argc, char *argv[])
{
char cinput[][8] = {"4.99","1.06","*","5.99","+","6.99","1.06","*","+"};
stack <double>st;
double pre;
double pre_pre;
double result;
cout << "size = "<<sizeof(cinput)/8 <<endl;
for(int i = 0;i<sizeof(cinput)/8;i++)
{
if (!strcmp(cinput[i],"*"))
{
pre = st.pop();
pre_pre = st.pop();
result = pre * pre_pre;
st.push(result);
}
else if (!strcmp(cinput[i],"+"))
{
pre = st.pop();
pre_pre = st.pop();
result = pre + pre_pre;
st.push(result);
}
else if (!strcmp(cinput[i],"-"))
{
pre = st.pop();
pre_pre = st.pop();
result = pre - pre_pre;
st.push(result);
}
else if (!strcmp(cinput[i],"/"))
{
pre = st.pop();
pre_pre = st.pop();
result = pre / pre_pre;
st.push(result);
}
else
{
st.push(atof((const char *)cinput[i]));
}
}
cout << st.TopOut() << endl;
return 0;
}