单链表实现的栈

 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/archive/2012/06/25/2562796.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值