53 lines
1.3 KiB
C
53 lines
1.3 KiB
C
|
#ifndef STACK2QUEUE_H
|
||
|
#define STACK2QUEUE_H
|
||
|
|
||
|
#include "LinkedStack.h"
|
||
|
#include "Queue.h"
|
||
|
#include <initializer_list>
|
||
|
|
||
|
namespace Kylin {
|
||
|
template <typename T>
|
||
|
class StackToQueue : public Queue<T> {
|
||
|
public:
|
||
|
StackToQueue(std::initializer_list<T> init) {
|
||
|
for (auto &value : init) enqueue(value);
|
||
|
}
|
||
|
void enqueue(const T &value) final { m_in.push(value); }
|
||
|
|
||
|
T dequeue() final {
|
||
|
if (size() <= 0) THROW_EXCEPTION(InvalidOperationException, "There is no element in the queue...");
|
||
|
auto value = head();
|
||
|
move();
|
||
|
m_out.pop();
|
||
|
return value;
|
||
|
}
|
||
|
T &head() final {
|
||
|
if (size() <= 0) THROW_EXCEPTION(InvalidOperationException, "There is no element in the queue...");
|
||
|
move();
|
||
|
return m_out.top();
|
||
|
}
|
||
|
|
||
|
virtual void clear() {
|
||
|
m_in.clear();
|
||
|
m_out.clear();
|
||
|
}
|
||
|
|
||
|
size_t size() const noexcept override { return m_in.size() + m_out.size(); }
|
||
|
|
||
|
protected:
|
||
|
void move() const {
|
||
|
if (m_out.size() <= 0) {
|
||
|
while (m_in.size() > 0) {
|
||
|
m_out.push(m_in.top());
|
||
|
m_in.pop();
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
private:
|
||
|
mutable LinkedStack<T> m_in;
|
||
|
mutable LinkedStack<T> m_out;
|
||
|
};
|
||
|
} // namespace Kylin
|
||
|
#endif // STACK2QUEUE_H
|