链接栈

 1 //
 2 //  Stack.h
 3 //  链接栈
 4 //
 5 //  Created by geshenglu on 2020/3/21.
 6 //  Copyright © 2020 geshenglu. All rights reserved.
 7 //
 8 
 9 #ifndef Stack_h
10 #define Stack_h
11 template<class Elemtype>
12 class Stack
13 {
14 public:
15     virtual bool IsEmpty() const =0;
16     virtual void Push(const Elemtype&x)=0;
17     virtual Elemtype Pop()=0;
18     virtual Elemtype Top()const =0;
19     virtual ~Stack(){};
20 };
21 #endif /* Stack_h */
 1 //
 2 //  LinkStack.h
 3 //  链接栈
 4 //
 5 //  Created by geshenglu on 2020/3/21.
 6 //  Copyright © 2020 geshenglu. All rights reserved.
 7 //
 8 
 9 #ifndef LinkStack_h
10 #define LinkStack_h
11 #include "Stack.h"
12 template<class Elemtype>
13 class LinkStack:public Stack<Elemtype>{
14 private:
15     struct Node{
16         Elemtype data;
17         Node *next;
18         Node(const Elemtype &x,Node *n = nullptr){
19             data = x;
20             next = n;
21         }
22         Node(){
23             next = nullptr;
24         }
25         ~Node(){}
26     };
27     Node *elem;
28 public:
29     LinkStack(){
30         elem = nullptr;
31     }
32     ~LinkStack();
33     virtual bool IsEmpty() const override;
34     virtual void Push(const Elemtype&x)override;
35     virtual Elemtype Pop()override;
36     virtual Elemtype Top()const override;
37 };
38 template<class Elemtype>
39 LinkStack<Elemtype>::~LinkStack(){
40     
41     while(elem!=nullptr){
42         Node *tmp = elem;
43         elem = elem->next;
44         delete tmp;
45     }
46 }
47 
48 template<class Elemtype>
49 bool LinkStack<Elemtype>::IsEmpty() const{
50     return elem == nullptr;
51 }
52 
53 template<class Elemtype>
54 void LinkStack<Elemtype>::Push(const Elemtype&x){
55     Node *tmp = new Node(x,elem);
56     elem = tmp;
57 }
58 
59 template<class Elemtype>
60 Elemtype LinkStack<Elemtype>::Pop(){
61     Node *tmp = elem;
62     Elemtype x = tmp->data;
63     elem = tmp->next;
64     delete tmp;
65     return x;
66 }
67 
68 template<class Elemtype>
69 Elemtype LinkStack<Elemtype>::Top()const{
70     return elem->data;
71 }
72 #endif /* LinkStack_h */
 1 //
 2 //  main.cpp
 3 //  链接栈
 4 //
 5 //  Created by geshenglu on 2020/3/21.
 6 //  Copyright © 2020 geshenglu. All rights reserved.
 7 //
 8 
 9 #include <iostream>
10 #include "LinkStack.h"
11 int main(int argc, const char * argv[]) {
12     LinkStack<int> stack;
13     for (int i=0; i<5; ++i)
14     {
15         stack.Push(i);
16     }
17     std::cout<<stack.Top()<<std::endl;
18     stack.Pop();
19     std::cout<<stack.Top()<<std::endl;
20     for (int i=0; i<10; ++i)
21     {
22         stack.Push(i+100);
23     }
24     std::cout<<stack.Top()<<std::endl;
25     return 0;
26 }

猜你喜欢

转载自www.cnblogs.com/jiangnansytle/p/12567076.html