We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Queue using Two Stacks
Queue using Two Stacks
+ 0 comments Python
Built a queue, therefore I didn't follow the instructions, but I wanted the practice building, essentially, a doubly linked list.
class Node: def __init__(self,data): self.data = data self.next = None self.prev = None class Queue: def __init__(self): self.head = None self.tail = None self.length = 0 def enque(self,data): node = Node(data) if self.head is None: self.head = node else: node.next = self.tail self.tail.prev = node self.tail = node self.length+=1 def deque(self): if len(self) < 1: return val = self.head.data if self.head.prev is None: self.head = None self.tail = None else: self.head = self.head.prev self.head.next = None self.length -= 1 def peek(self): if len(self) < 1: return val = self.head.data return int(val) def __len__(self): return self.length if __name__ == "__main__": DQ = Queue() for i in range(int(input())): quer = input() if quer[0] == '1': DQ.enque(int(quer[2:])) elif quer[0] == '2': DQ.deque() else: print(DQ.peek())
+ 0 comments Python solution using two stacks
s1 = [] s2 = [] def enqueue(x): s1.append(x) def dequeue(): s2.extend(s1[:0:-1]) s1.clear() s1.extend(s2[::-1]) s2.clear() def display(): print(s1[0]) n = int(input()) for _ in range(n): q = list(map(int,input().split())) if q[0]==1: enqueue(q[1]) elif q[0]==2: dequeue() else: display()
+ 0 comments My Python Solution:
q = int(input()) queue = [] for _ in range(q): ops = input().split() if ops[0] == '1': queue.insert(0,ops[1]) elif ops[0] == '2': queue.pop() else: print(queue[-1])
+ 0 comments My JS Solution:
function processData(input) { input = input.split('\n').slice(1); var queue = [] for(let q of input){ q = q.split(' '); if(q[0] === '1') queue.unshift(q[1]); else if(q[0] === '2') queue.pop(); else console.log(queue.at(-1)); } }
+ 1 comment Is there a point to this? Why would I implement a queue using two stacks?
Load more conversations
Sort 470 Discussions, By:
Please Login in order to post a comment