請使用 C++或 Java 程式庫中的 vector 類別,以泛型(generic)技術,設計一堆疊(Stack)物件,內含 push()、
pop()、isEmpty()及 atTop()等四項功能。評分準則如下:
(一)用泛型技術宣告此堆疊物件。【2 分】
(二)完成 push()方法設計。【2 分】
(三)完成 pop()方法設計。【2 分】
(四)完成 isEmpty()方法設計。【2 分】
(五)完成 atTop()方法設計。【2 分】
// stack.cpp : Defines the entry point for the console application.
//
#include "stack.h"
#include <iostream>
#include <vector>
using namespace std;
int main() {
        const int stk_size = 10;
        stack intStack;
        int ix = 0;
        while(intStack.size() != stk_size) {
          intStack.push(ix++);
        }
        int error_cnt = 0;
        while(intStack.isEmpty() == false) {
                int value = intStack.atTop();
            cout << "the value of the top element is " << value << endl;
                intStack.pop();
        }
        return 0;
}
// stack.cpp: implementation of the stack class.
//
//////////////////////////////////////////////////////////////////////
#include "stack.h"
#include <iostream>
#include <vector>
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
stack::stack()
{               
}
stack::~stack()
{
}
int stack::atTop() 
{
        //return *--v.end();
        return *(v.end()-1);
}
bool stack::isEmpty() 
{
        return v.empty();
}
void stack::push(int value) 
{
        v.push_back(value);
}
int stack::pop() 
{
        int value = this->atTop();
        cout << "Pop " << this->atTop() << endl;
        v.pop_back();
        return value;
}
int stack::size() 
{
        return v.size();
}
// stack.h: interface for the stack class.
//
//////////////////////////////////////////////////////////////////////
#include <vector>
//typedef int E;
class stack  
{
public:
        int size();
        stack();
        virtual ~stack();
        void push(int);
        int pop();
        bool isEmpty();
        int atTop();
private:
        std::vector<int> v;   
};
 
 
 
 
No comments:
Post a Comment