本文共 3045 字,大约阅读时间需要 10 分钟。
思考:栈和队列在实现上非常相似,能否用相互实现?
用栈实现队列等价于用“后进先出”的特性实现“先进先出”的特性.
实现思路:template < typename T >class StackToQueue : public Queue{protected: mutable LinkStack m_stack_in; mutable LinkStack m_stack_out; void move() const //O(n) { if(m_stack_out.size() == 0) { while(m_stack_in.size() > 0) { m_stack_out.push(m_stack_in.top()); m_stack_in.pop(); } } }public: void enqueue(const T& e) //O(1) { m_stack_in.push(e); } void dequeue() //O(n) { move(); if(m_stack_out.size() > 0) { m_stack_out.pop(); } else { THROW_EXCEPTION(InvalidOperationException, "no element in current StackToQueue..."); } } T front() const //O(n) { move(); if(m_stack_out.size() > 0) { return m_stack_out.top(); } else { THROW_EXCEPTION(InvalidOperationException, "no element in current StackToQueue..."); } } void clear() // O(n) { m_stack_in.clear(); m_stack_out.clear(); } int length() const //O(n) { return m_stack_in.size() + m_stack_out.size(); }};
评价:
虽然可以使用栈实现队列,但是相比直接使用链表实现队列,在出队和获取对头元素的操作中,时间复杂度都变为了O(n),可以说并不高效。使用队列实现栈,本质上就是使用“先进先出”的特性实现栈“后进先出”的特性。
实现思路:template < typename T >class QueueToStack : public Stack{protected: LinkQueue m_queue_in; LinkQueue m_queue_out; LinkQueue * m_qIn; LinkQueue * m_qOut; void move() const //O(n) { while(m_qIn->length()-1 > 0) { m_qOut->enqueue(m_qIn->front()); m_qIn->dequeue(); } } void swap() //O(1) { LinkQueue * temp = NULL; temp = m_qIn; m_qIn = m_qOut; m_qOut = temp; }public: QueueToStack() //O(1) { m_qIn = &m_queue_in; m_qOut = &m_queue_out; } void push(const T& e) //O(n) { m_qIn->enqueue(e); } void pop() //O(n) { if(m_qIn->length() > 0) { move(); m_qIn->dequeue(); swap(); } else { THROW_EXCEPTION(InvalidOperationException, "no element in current QueueToStack..."); } } T top() const //O(n) { if(m_qIn->length() > 0) { move(); return m_qIn->front(); } else { THROW_EXCEPTION(InvalidOperationException, "no element in current QueueToStack..."); } } void clear() //O(n) { m_qIn->clear(); m_qOut->clear(); } int size() const //O(1) { return m_qIn->length() + m_qOut->length(); }};
总结评价:
虽然可以使用队列实现栈,但是相比直接使用链表实现栈,入栈、出栈、获取栈顶元素操作中,时间复杂度都变为了O(n),可以说并不高效。转载于:https://blog.51cto.com/11134889/2131771