# Stack using two queues

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

#### ilushka Profile Answers by ilushka

• Nov 3rd, 2011

Something like this:

```Codequeue_t q0;
queue_t q1;

void stack_push(void *t) {
// At any given time one queue will be empty
queue_t *curr = (q0.size() ? q0 : q1);

curr.push(t);
}

void *stack_pop() {
// curr - queue with all the elementsm
// next - empty queue that will get n-1 elemets
queue_t *curr, *next;

if (q0.size()) {
curr = q0;
next = q1;
} else {
curr = q1;
next = q0;
}

// "Copy" all the elements except last
while (curr.size() != 1) {
next.push(curr.pop());
}

return curr.pop();
}```

#### ptmich Profile Answers by ptmich

• May 28th, 2012

```Code1.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.isEmpty() ? q1 : q0);
7.
8.  curr.push(t);
9.}
10.
11.void *stack_pop() {
12.  // curr - queue with all the elements
13.  // next - empty queue that will get n-1 elemets
14.  queue_t *curr, *next;
15.
16.  if (q0.isEmpty()) {
17.    curr = q1;
18.    next = q0;
19.  } else {
20.    curr = q0;
21.    next = q1;
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.}```