随笔-13  评论-0  文章-2  trackbacks-0
 1/**
 2        Stack(use linked structure 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
16using namespace std;
17#ifndef STACK_H
18#define STACK_H
19
20template<typename T>
21struct Node
22{
23    T data;
24    Node* next;
25}
;
26
27template<typename T>
28class Stack
29{
30public:
31    Stack();
32    ~Stack();
33    bool Empty() const return top->next == NULL; }
34    int  Size() const return size; }
35    void Push(const T&);
36    void Pop();
37    void Print() const;
38private:
39    Node<T>* top;
40    int size;
41
42}
;
43
44template<typename T> Stack<T>::Stack()
45{
46    top = new Node<T>;
47    top->next = NULL;
48    size = 0;
49}

50
51template<typename T> Stack<T>::~Stack()
52{
53    assert(top->next->next != NULL);
54    forint i = 0; i < size; i++ )
55    {
56        Pop();
57        size--;
58    }

59}

60
61template<typename T> void Stack<T>::Push(const T& one)
62{
63    Node<T>*new_node = new Node<T>;
64    new_node->data = one;
65    new_node->next = top;
66    top = new_node;
67    size++;
68}

69
70template<typename T> void Stack<T>::Pop()
71{
72    Node<T>* p = new Node<T>;
73    p = top;
74    top = top -> next;
75    delete p;
76    p = NULL;
77    size--;
78}

79
80template<typename T> void Stack<T>::Print() const
81{
82    cout << "Reverse inputing" << endl;
83    Node<T>* p = new Node<T>;
84     p = top;
85    for(int i = 0; i < size; i++)
86    {
87        cout << p ->data << " " ;
88        p = p-> next;
89    }

90    cout << endl;
91
92}

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

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

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

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

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