随笔-13  评论-0  文章-2  trackbacks-0
 1/**
 2        Stack(use array to implement)
 3        Version: 1.0
 4        Member function as follow:
 5        size()
 6        push(T)        // inset an elm
 7        pop()        // delete the last elm
 8        empty()         // if it is an empty list
 9        print()
10
11        Use C++ template
12**/

13#include<iostream>
14#include<string>
15
16
17using namespace std;
18#ifndef SQSTACK_H
19#define SQSTACK_H
20
21template<typename T>
22class sqStack
23{
24public:
25    sqStack():top(-1){}
26    ~sqStack(){ top = -1; };
27    bool Empty()const return top == -1; }
28    void Push(const T&);
29    void Pop(){ assert(top > -1); top--;};
30    void Print() const;
31    int  Size() const return (top + 1);};
32private:
33    static const int MaxSize = 200;
34    T elem[MaxSize];
35    int top;
36}
;
37
38template<typename T> void sqStack<T>::Push(const T& one)
39{
40    assert(top <= MaxSize - 1);
41    top++;
42    elem[top] = one;
43}

44
45template<typename T> void sqStack<T>::Print() const
46{
47    for(int i = 0; i < top; i++ )
48    cout << elem[i] << " ";
49    cout << elem[top] << endl;
50}

51
52#endif

//Test Function
 1// Test Function
 2int main()
 3{
 4    using namespace std;
 5    sqStack<int> stack;
 6    cout << "----------------Display the stack program-----------------------" << endl;
 7    cout << "\n Initial the stack,please input the number of element to push stack "<< endl;
 8    cout << "number = " ;
 9    int number;
10    cin >> number;
11    cout << "Secondly input the number in the following\n" << endl;
12    int temp;
13    forint i = 0; i < number; i++ )
14    {
15        cin >> temp;
16        stack.Push(temp);
17    }

18    cout << "You Input As Follow" << endl;
19    stack.Print();
20    cout << "Would you like to display the pop functionYes or No" << endl;
21    string answer;
22    cin >> answer;
23    if( answer == "yes" || answer == "YES" )
24    {
25        stack.Pop();
26        stack.Print();
27    }

28    cout <<"-----------------------------------------------------------------" << endl;
29    system("pause");
30    return 0;
31
32}

33

posted on 2009-03-18 22:44 亦夏 阅读(227) 评论(0)  编辑 收藏 引用 所属分类: DataStruct

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理