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;
    }
    
    
    


    版权声明:

  • 相关阅读:
    html5不能播放视频的方法
    mysql找出重复数据的方法
    jquery each循环遍历完再执行的方法
    Android:TextView跑马灯-详解
    日志处理(一) log4j 入门和详解(转)
    周记 2014.11.08
    周记 2014.11.01
    linux下解压命令大全
    关于Context []startup failed due to previous errors
    周记 2014.10.25
  • 原文地址:https://www.cnblogs.com/walccott/p/4956919.html
Copyright © 2011-2022 走看看