Stack using two queues

Write a code how to implement stack using two queues?
and vice versa ?

Showing Answers 1 - 0 of 0 Answers

ilushka

  • Nov 3rd, 2011
 

Something like this:

Code
  1. queue_t q0;

  2. queue_t q1;

  3.  

  4. void stack_push(void *t) {

  5.   // At any given time one queue will be empty

  6.   queue_t *curr = (q0.size() ? q0 : q1);

  7.  

  8.   curr.push(t);

  9. }

  10.  

  11. void *stack_pop() {

  12.   // curr - queue with all the elementsm

  13.   // next - empty queue that will get n-1 elemets

  14.   queue_t *curr, *next;

  15.  

  16.   if (q0.size()) {

  17.     curr = q0;

  18.     next = q1;

  19.   } else {

  20.     curr = q1;

  21.     next = q0;

  22.   }

  23.  

  24.   // "Copy" all the elements except last

  25.   while (curr.size() != 1) {

  26.     next.push(curr.pop());

  27.   }

  28.  

  29.   return curr.pop();

  30. }

ptmich

  • May 28th, 2012
 

Code
  1. 1.queue_t q0;

  2. 2.queue_t q1;

  3. 3.

  4. 4.void stack_push(void *t) {

  5. 5.  // At any given time one queue will be empty

  6. 6.  queue_t *curr = (q0.isEmpty() ? q1 : q0);

  7. 7.

  8. 8.  curr.push(t);

  9. 9.}

  10. 10.

  11. 11.void *stack_pop() {

  12. 12.  // curr - queue with all the elements

  13. 13.  // next - empty queue that will get n-1 elemets

  14. 14.  queue_t *curr, *next;

  15. 15.

  16. 16.  if (q0.isEmpty()) {

  17. 17.    curr = q1;

  18. 18.    next = q0;

  19. 19.  } else {

  20. 20.    curr = q0;

  21. 21.    next = q1;

  22. 22.  }

  23. 23.  

  24. 24.  // "Copy" all the elements except last

  25. 25.  while (curr.size() != 1) {

  26. 26.    next.push(curr.pop());

  27. 27.  }

  28. 28.

  29. 29.  return curr.pop();

  30. 30.}


  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions