Hey everyone, I am working on a problem in which I have to define astack in term
ID: 3612565 • Letter: H
Question
Hey everyone, I am working on a problem in which I have to define astack in terms of a queue. I actually think I have figured itout. I was just wondering if someone could double check mywork. (Note: the queue is the one defined in the StandardTemplate Library)//Code*********************************************************
template <class T>
class Stack {
private:
queue<T> pool;
public:
Stack(){} // inline constructor
~Stack(){} // inline destructor
void push(const T& el);
void pop() { pool.pop(); } // end pop()
void clear();
T& topEl() { return pool.front(); } // endtopEl()
int size() { return pool.size(); } // endsize()
bool isEmpty() { return pool.empty(); } // endisEmpty()
};
template<class T>
void Stack<T> :: push(const T& el){
queue<T> temp;
while(!pool.empty()) { // empty pool into tempqueue if it is not empty
temp.push(pool.front());
pool.pop();
}
pool.push(el); // push the new value into poolqueue
while(!temp.empty()) { // empty temp queue backinto pool queue
pool.push(temp.front());
temp.pop();
}
} // end push()
template<class T>
void Stack<T> :: clear() {
while(!pool.empty()) {
pool.pop();
}
} // end clear()
//Code*********************************************************
Explanation / Answer
Your program is logically correct. POP deletes the first element of the QUEUE..which is required. In PUSH also, you are inserting the New element at the Head of thequeue. Remaining functions are also correct.