Sword Point offer: Two stacks to implement a queue

Source: Internet
Author: User

Title: Implement a queue with two stacks. Implement its two functions Appendtail and Deletehead, respectively, to complete the function of inserting nodes at the end of the queue and deleting nodes at the head of the queue. The declaration of the queue is as follows:
  
 
  1. template <typename T> class CQueue
  2. {
  3. public:
  4. CQueue(void);
  5. ~CQueue(void);
  6. // 在队列末尾添加一个结点
  7. void appendTail(const T& node);
  8. // 删除队列的头结点
  9. T deleteHead();
  10. private:
  11. stack<T> stack1;
  12. stack<T> stack2;
  13. };


  
 
  1. template<typename T> void CQueue<T>::appendTail(const T& element)
  2. {
  3. stack1.push(element);
  4. }
  5. template<typename T> T CQueue<T>::deleteHead()
  6. {
  7. if(stack2.size()<= 0)
  8. {
  9. while(stack1.size()>0)
  10. {
  11. T& data = stack1.top();
  12. stack1.pop();
  13. stack2.push(data);
  14. }
  15. }
  16. if(stack2.size() == 0)
  17. throw new exception("queue is empty");
  18. T head = stack2.top();
  19. stack2.pop();
  20. return head;
  21. }






From for notes (Wiz)

Sword Point offer: Two stacks to implement a queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.