您的位置:首页 > 编程语言 > C语言/C++

用C++实现STL容器stack

2015-10-18 10:53 489 查看
template<class Object>
class Stack
{
public:
enum{STACK_SIZE = 20};
Stack(int n = 0):stack_top(0){ theSize = n + STACK_SIZE; st = new Object[theSize]; }
~Stack(){delete [] st;}
typedef Object * iterator;
typedef const Object * const_iterator;

iterator push(const Object & obt){
if (stack_top == theSize-1)
{
resize(2 * stack_top + 1);
}
st[stack_top] = obt;
stack_top++;
return &st[stack_top];
}

iterator pop(){
if(empty()){
printf("the stack is empty.\n");
return &st[0];
}
stack_top--;
return &st[stack_top];
}

Object & top() const{
if(empty()){
printf("the stack is empty.\n");
return st[0];
}
return st[stack_top-1];
}

bool empty() const{
if (stack_top == 0)
return true;
else
return false;
}
void resize(int newSize){
Object * oldObject = st;
st = new Object[newSize];
for (int i = 0; i < stack_top; i++){
st[i] = oldObject[i];
}

delete [] oldObject;
}

int size() const{
return top-1;
}
private:
int stack_top;
int theSize;
Object * st;
};


#include "stack.h"
#include <iostream>

using namespace std;

int main()
{
Stack<int> s;

if (s.empty())
cout << "the stack is empty.\n";
else
cout << "the stack is not empty.\n";

s.push(1);
s.push(2);
s.push(3);
s.push(4);
if (s.empty())
cout << "the stack is empty.\n";
else
cout << "the stack is not empty.\n";;

cout << "stack top element is " << s.top() << endl;

s.pop();
cout << "After the pop, the top element is " << s.top() << endl;

/*判断输入的括号是不是成对出现;输入括号符号,当输入为q或Q的时候退出*/
Stack<char> char_stack;
char ch;
while(cin >> ch && ch != 'q' && ch != 'Q'){
switch (ch)
{
case '(': char_stack.push(ch);break;
case ')': if (char_stack.top() == '(') char_stack.pop();
else char_stack.push(ch);
break;
case '[': char_stack.push(ch);break;
case ']': if (char_stack.top() == '[') char_stack.pop();
else char_stack.push(ch);
break;
case '{': char_stack.push(ch);break;
case '}': if (char_stack.top() == '{') char_stack.pop();
else char_stack.push(ch);
break;
default: break;
}
}

if(char_stack.empty())
cout << "the input is right.\n";
else
cout << "the input is wrong.\n";

system("pause");
exit(0);
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: