Stackã使ã£ã¦Queueãä½ã
æåãªè©±ãã¨æã£ããæå¤ã¨ç¥ããã¦ããªãã£ãã®ã§ã¡ã¢ã
FILOã使ã£ã¦FIFOãä½ãã¨ãè¨ãã¾ããStackã§Queueä½ãã¦ãQueueã§Stackãä½ãæ¹æ³ãæãã¤ããªãã®ã§èª°ãæãã¦ä¸ããããããã¯ããããå¦åããã£ããç´¹ä»ãã¦é ããã¨å¬ããã§ãã
ç°¡åãªèª¬æã¨ãã¦ã¯ã2ã¤ã®Stackãç¨æãã¦ãenqueueããã¨ãã«ã¯1ã¤ç®ã«push()ããdequeueããã¨ãã«ã¯2ã¤ç®ããpop()ããã ãã
ãã ã2ã¤ç®ã®Stackã空ã®å ´åã¯1ã¤ç®ã®ã¹ã¿ãã¯ã空ã«ãªãã¾ã§2ã¤ç®ã®ã¹ã¿ãã¯ã«ç§»ãæ¿ããã
template<typename T> class MyQueue { std::stack<T> in, out; MyQueue(){} void enqueue(const T& v) { in.push(v); } T dequeue() { if (out.empty()) { if (in.empty()) { throw std::exception("Queue is empty!"); } while (!in.empty()) { out.push(in.top()); in.pop(); } } T result = out.top(); out.pop(); return result; } };
å³ã«æ¸ãã¨ãããªæãã
å®éã«ãã¼ã¿ã貯ãã¦ã¿ããenqueue(1);enqueue(2);enqueue(3);
Stackãªã®ã§æåã«å
¥ãããã¼ã¿ãä¸çªåºã«æ²ãã
ããããdequeueãã¦ã¿ããoutå´ã®stackã空ãªã®ã§inå´ããæã£ã¦æ¥ãå¿
è¦ãããã
ããã§outå´ã®stackãè¦ãã¨ããä¸æè°ãæåã«å
¥ãããã®ãStackã®ä¸çªä¸ã«ããããpop()ããã°dequeueã§ããã