Queue using Two Stacks

  • + 0 comments

    Python solution, i tried use the more pure stack definition.

    class Stack():
        def __init__(self):
            self.my_stack = []
            self.head = -1
            self.opr_limit = 100
            self.bottow_el = None
            self.size = 0
            
        def stack(self, val):
            self.my_stack.append(val)
            self.head += 1
            self.size += 1
            if self.head == 0:
                self.bottow_el = val
                
        def unstack(self):
            val = self.my_stack[self.head]
            del self.my_stack[self.head]
            self.head -= 1
            self.size -= 1
            if self.head < 0:
                self.bottow_el = None
            
            return val
            
        def get_bottow(self):
            return self.bottow_el
            
        def get_top(self):
            return self.my_stack[self.head]
            
        def tostr(self):
            return (self.my_stack)
            
    n_queries = int(input())
    stack_1 = Stack()
    stack_2 = Stack()
    
    for e in range(n_queries):
        query_s = str(input()).split()
        
        if query_s[0] == "1":
            stack_1.stack(int(query_s[1]))
            
        elif query_s[0] == "2":
            if stack_2.size > 0:
                stack_2.unstack()
            else:
                for e in range(stack_1.size):
                    stack_2.stack(stack_1.unstack())
                stack_2.unstack()
        else:
            if stack_2.size > 0:
                print(stack_2.get_top())
                
            else:
                print(stack_1.get_bottow())