栈的实现算是非常简单的。
STL中实际上也由stack的容器,因此,重复造轮子是完全没有必要的。
实现一下栈可以帮助我们更好的理解栈的应用和结构
以下是栈的代码:
stack.h
#pragma once #include<bits/stdc++.h> template<typename E>class Stack //栈的顺序实现 { private: void Assert(bool a, std::string b) //断言函数 { if (!a) { std::cout << b << std::endl; } } int maxsize;//最大容量 int top;//栈顶索引 E* listArrey;//数组 public: Stack(int size = 20)//构造函数,默认大小为20 { maxsize = size; top = 0;//栈顶为0,即还没有放元素 listArrey = new E[size]; } ~Stack() { delete[] listArrey; } void clear() { //清空栈 top = 0; } void push(const E& it) { //压栈 Assert(top != maxsize, "Stack is full"); listArrey[top++] = it;//操作顺序是:先赋值,再自增,top会一直指向一个空位置 } E pop() { Assert(top != 0, "Stack is empty"); return listArrey[--top];//操作顺序:先自减,再返回 } const E& topValue() { //取栈顶元素但是不删除 Assert(top != 0, "Stack is empty"); return listArrey[top - 1]; } int length() { //读取堆中已占用的长度 return top; } void print() { for (int i = 0; i < length(); i++) { std::cout << listArrey[i] << " "; } std::cout << std::endl; } void adjust(int n) { //用于调整栈的大小 Assert(n>length(),"New size is too small"); maxsize = n; listArrey = new E[n]; } };
test.cpp
#include"Stack.h" int main() { Stack<int> a; for (int i = 1; i <= 10; i++) { a.push(i); } a.print(); while (a.topValue()!= 5 ) { std::cout << a.pop() << std::endl; } a.print(); a.adjust(6); return 0; }
测试结果