单链表实现的栈

 1 #ifndef STACK_H
 2 #define STACK_H
 3 
 4 #include<stdexcept>
 5 #include<string>
 6 using namespace std;
 7 
 8 template<typename T>
 9 class Stack
10 {
11 private:
12     template<typename T>
13     struct Node
14     {
15         T data;
16         Node* next;
17         Node(T data,Node* next):data(data),next(next){}
18     };
19 
20     Node<T>* _top;
21 public:
22     class StackEmptyException:public logic_error{
23     public:
24         StackEmptyException(const string& msg=""):logic_error(msg){}
25     };
26 
27     Stack(){
28         _top=0;
29     }
30 
31     ~Stack(){
32         while(_top){
33             Node* next=_top->next;
34             delete _top;
35             _top=next;
36         }
37     }
38 
39     void push(T data){
40         _top=new Node<T>(data,_top);
41     }
42     
43     bool isEmpty(){
44         return _top==0;
45     }
46 
47     T top() throw(StackEmptyException){
48         if(!isEmpty())
49             return _top->data;
50         else
51             throw StackEmptyException();
52     }
53 
54     void pop() throw(StackEmptyException){
55         if(!isEmpty()){
56             Node<T>*next=_top->next;
57             delete _top;
58             _top=next;
59         }
60         else
61             throw StackEmptyException();
62     }
63 };
64 
65 #endif//STACK_H

欢迎大家批评指正哦O(∩_∩)O~

原文地址:https://www.cnblogs.com/freewater/p/2562796.html