zoukankan      html  css  js  c++  java
  • 重学数据结构系列之——栈

    学习来源:计蒜客

    1.栈


    在以后的重学数据结构系列,为了废话没那么多,就不复制百度百科等的了。直接用自己的话来说。

    1.栈是什么


    你就想象一个园桶,从上到下的直径都是一样的,我们向里面放入刚好能放入的圆碟,直到桶碟满,然而你只能从最上面的园碟开始拿。这就可以叫做栈
    最重要的是先进后出,First In Last Out(FILO)。

    2.栈的实现

    #include<iostream>
    #include<string>
    #include <cassert>
    
    using namespace std;
    
    template<class Type> class Stack{
    private:
    	Type *elements;
    	int max_size, top_index;
    public:
    	//构造函数
    	Stack(int length_input){
    		elements = new Type[length_input];
    		max_size = length_input;
    		top_index = -1;
    	}
    	//析构函数
    	~Stack(){
    		delete[] elements;
    	}
    	//入栈
    	bool push(const Type &element){
    		//是否超过栈容量
    		if (top_index >= max_size-1) {
    			return false;
    		}
    		//栈顶向上移,并赋值
    		top_index++;
    		elements[top_index] = element;
    		return true;
    	}
    	//出栈
    	bool pop(){
    		//判断栈是否为空
    		if (top_index < 0) {
    			return false;
    		}
    		//栈顶向下移
    		top_index--;
    		return true;
    	}
    	//获取栈顶元素
    	Type top(){
    		assert(top_index >= 0);
    		return elements[top_index];
    		//或者 
    		//if (!empty()) {
    		//	return elements[top_index];
    		//}else{
    		//	exit("there is no element");
    		//}
    	}
    	//判断栈是否为空
    	bool empty(){
    		if (top_index < 0) {
    			return true;
    		}else{
    			return false;
    		}
    	}
    };
    
    int main() {
    	int n;
    	string str;
        cin >> n;
    	Stack<string> stack(n); 
    	for (int i = 0; i < n; i++) {
    		cin >> str;
    		stack.push(str);
    	}
    	for (i = 0; i < n; i++) {
    		cout<<stack.top()<<" ";
    		stack.pop();
    	}
    	cout<<endl;
    	
    
        return 0;
    }

    3.运行结果



    4.小总结

    可以看到,用栈进行一些翻转操作非常方便,逆序输出,数组的reverse等

    5.用程序判断出栈顺序是否可能





  • 相关阅读:
    生成器 和 生成器 表达式
    函数的三大器
    02.python网络爬虫第二弹(http和https协议)
    python网络爬虫第三弹(<爬取get请求的页面数据>)
    线程
    网络编程
    分时操作系统 与 多道程序系统
    javascript原型深入解析2--Object和Function,先有鸡先有蛋
    javascript原型深入解析1-prototype 和原型链、js面向对象
    js模块化
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286560.html
Copyright © 2011-2022 走看看