用C++實現STL容器stack

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);
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章