Monday, February 10, 2014

queue with 2 stacks, stack with 2 queues

queue with 2 stacks. for enqueue, out->in and push into in. for dequeue, in->out and pop from out.
enqueue(x):
    while !out.isEmpty():
        in.push(out.pop())
    in.push(x)

x dequeue():
    while !in.isEmpty():
        out.push(in.pop())
    return out.pop()
Elements in out are already in dequeue order so no need to move to in.
enqueue(x):
    in.push(x)

x dequeue():
    if !out.isEmpty():
        while !in.isEmpty():
            out.push(in.pop())
    return out.pop()

stack with 2 queues. for push, enqueue into non-empty queue (or q2). for pop, dequeue all from non-empty queue, enqueue into other and return last.

push(T x):
    if !q1.isEmpty():
        q = q1
    else
        q = q2
    q.enqueue(x)

T pop():
    if q1.isEmpty() && q2.isEmpty():
        throw "empty"
    if !q1.isEmpty():
        q = q1
        other = q2
    else
        q = q2
        other = q1
    n = null
    while !q.isEmpty():
        n = q.dequeue()
        if q.isEmpty():
            break;
        other.enqueue(n)
    return n

No comments:

Post a Comment