zoukankan      html  css  js  c++  java
  • STL学习之stack

    栈是一种容器适配器,是一种后入先出(LIFO )队列。

    基本操作

    stack<int>s;构造

    stack<int>s1(s2);将s2赋值给s1

    s.push(x);入栈

    s.pop();出栈,注意:出栈操作只是删除栈顶的元素,并不返回该元素

    s.top();访问栈顶

    s.empty().判断栈空,当栈空时返回true

    s.size();栈中的元素个数


    问题:用stack实现FIFO的功能


    // FIFObuildinStack.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include<stack>
    #include<iostream>
    using namespace std;
    class FIFO
    {
    private:
    		stack<int>a;
    	    stack<int>b;
    public:
    	//FIFO();
    	void enqueue(int in);
    	int dequeue();
    	bool isempty();
    	//~FIFO();
    };
    void FIFO::enqueue(int in)//入队
    {
    	int k;
    	while (!b.empty())
    	{
    		k = b.top();
    		a.push(k);
    		b.pop();
    	}
    	a.push(in);
    }
    
    int FIFO::dequeue()//出队
    {
    	int cc;
    	while (!a.empty())
    	{
    		cc = a.top();
    		a.pop();
    		b.push(cc);
    	}
    	int bb = b.top();
    	b.pop();
    	return bb;
    }
    bool FIFO::isempty()
    {
    	return(a.empty() && b.empty());
    
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
    	FIFO fifo;
    	fifo.enqueue(1);
    	fifo.enqueue(3);
    	fifo.enqueue(8);
    	cout << fifo.dequeue() << endl;
    	cout << fifo.dequeue() << endl;
    	if (fifo.isempty())
    		cout << "现在FIFO为空" << endl;
    	cout << fifo.dequeue() << endl;
    	if (fifo.isempty())
    		cout << "现在FIFO为空" << endl;
    	system("pause");
    	return 0;
    }
    
    
    


    版权声明:

  • 相关阅读:
    JS身份证真实性校验(一)
    Python之文件操作
    python之数据类型
    Python之循环条件、变量、字符串格式化
    webpack之proxyTable设置跨域
    vue报错解决方案
    CentOS 7 下Ansiable搭建命令列表 及常用监控指令
    CentOS 7 下nagios搭建记录
    弹窗鼠标拖动功能-js
    做好探索性测试,体现你的价值
  • 原文地址:https://www.cnblogs.com/walccott/p/4956919.html
Copyright © 2011-2022 走看看