Queue using Two Stacks

Sort by

recency

|

56 Discussions

|

  • + 0 comments

    There's a typo in the sample input.

    1 14 enqueue 42

    This line should read

    1 14 enqueue 14

  • + 0 comments
    q = []
    for s in [input() for _ in range(int(input()))]:
        q.append(s[2:]) if s[0] == '1' else q.pop(0) if s == '2' else print(q[0]) if s == '3' else ...
    
  • + 0 comments

    here is hackerrank queue using two stacks problem solution in Python, Java, C++, C and javascript

  • + 0 comments

    Skipped this one as I didn't want to write all the reading code. Regardles the idea for the implementation

    • enqueue = push to inStack
    • dequeue = iff outStack is empty pop everything from inStack while pushing to outStack; pop from outStack

    time complexity: enqueue is constant O(1) dequeue is also constant O(2) -- while taking any single element from the queue is linear in worst case (when outStack is empty), amortised complexity (taking N elementes) will result in 2 operations per element (one to move the element from inStack to outStack and one to take it from the outStack).

    de

  • + 0 comments
    class Stack:
        def __init__(self):
            self.items = []
            
        def push(self, x):
            self.items.append(x)
        
        def pop(self):
            if self.items:
                return self.items.pop()
            else:
                return None
                
        def top(self):
            if self.items:
                return self.items[-1]
            else:
                return None
                
    class Queue:
        def __init__(self):
            self.en_st = Stack()  # enqueue stack
            self.de_st = Stack()  # dequeue stack
            
        def enqueue(self, x):
            self.en_st.push(x)
            
        def dequeue(self):
            if not self.de_st.items:
                while self.en_st.items:
                    self.de_st.push(self.en_st.pop())
            return self.de_st.pop()
        
        def front(self):
            if not self.de_st.items:
                while self.en_st.items:
                    self.de_st.push(self.en_st.pop())
            return self.de_st.top()
    
    queue = Queue()
    count = int(input())
    for _ in range(count):
        order = input().split()
        if order[0] == '1':
            queue.enqueue(int(order[1]))
        elif order[0] == '2':
            queue.dequeue()
        elif order[0] == '3':
            print(queue.front())
        else:
            print('Error code: 999')
            break