Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement A Queue using Two Stacks Python

I've been going over some of the many coding interview questions. I was wondering how you would go about implementing a queue using two stacks in Python? Python is not my strongest language so I need all the help I can get.

Like the enqueue, dequeue, and front functions.

like image 381
user3424438 Avatar asked Jun 30 '26 15:06

user3424438


2 Answers

class Queue(object):
    def __init__(self):
        self.instack=[]
        self.outstack=[]
    def enqueue(self,element):
        self.instack.append(element)
    def dequeue(self):
        if not self.outstack:
            while self.instack:
                self.outstack.append(self.instack.pop())
        return self.outstack.pop()
q=Queue()
for i in range(10):
    q.enqueue(i)
for i in xrange(10):
    print q.dequeue(),
like image 196
Pankaj Chaudhary Avatar answered Jul 03 '26 04:07

Pankaj Chaudhary


class MyQueue(object):
    def __init__(self):
        self.first = []
        self.second = []

    def peek(self):
        if not self.second:
            while self.first:
                self.second.append(self.first.pop());
        return self.second[len(self.second)-1];


    def pop(self):
        if not self.second:
            while self.first:
                self.second.append(self.first.pop());
        return self.second.pop();

    def put(self, value):
        self.first.append(value);


queue = MyQueue()
t = int(raw_input())
for line in xrange(t):
    values = map(int, raw_input().split())

    if values[0] == 1:
        queue.put(values[1])        
    elif values[0] == 2:
        queue.pop()
    else:
        print queue.peek()
like image 28
Urvashi Gupta Avatar answered Jul 03 '26 06:07

Urvashi Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!