当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++ 栈 (数组实现)

C++ 栈 (数组实现)

2018年12月25日  | 移动技术网IT编程  | 我要评论

马夫哥,潜伏惊骇,人造板生产线

上一篇用链表实现了stack,这篇我们采用数组来存储数据,数组更容易理解,直接贴代码

第一、代码实现

 1 #pragma once
 2 #include <iostream>
 3 using namespace std;
 4 template <typename t> class stackarray {
 5 public:
 6     stackarray(int size) {
 7         this->top = -1;
 8         this->maxsize = size;
 9         elements = new t[size];
10     }
11     ~stackarray() {
12         delete [] elements;
13     }
14     bool push(t t);
15     t pop();
16     bool isempty();
17     void print();
18 
19 private:
20     int top = -1;
21     int maxsize;
22     t* elements;
23 
24 };
25 
26 template<typename t>
27 bool stackarray<t>::push(t data) {
28     if (top==maxsize)
29     {
30         return false;
31     }
32     elements[++top] = data;
33     return true;
34 }
35 
36 template<typename t>
37 t stackarray<t>::pop() {
38     if (top==-1)
39     {
40         exit(-1);
41     }
42     return elements[top--];
43 }
44 
45 template<typename t>
46 bool stackarray<t>::isempty() {
47     return top == -1;
48 }
49 
50 template<typename t>
51 void stackarray<t>::print() {
52     int loop = top;
53     while (loop>=0)
54     {
55         cout << elements[loop] << endl;
56         loop--;
57     }
58 }
view code

第二、测试运行

 1 #include "pch.h"
 2 #include "stackarray.h"
 3 #include <iostream>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     stackarray<int> stack(10);
 9     stack.push(1);
10     stack.push(3);
11     stack.push(10);
12     stack.push(40);
13     stack.pop();
14     stack.push(30);
15 
16     stack.print();
17 
18     std::cout << "hello world!\n"; 
19 }
view code

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网