publicclassQueueToStack{ publicstaticvoidmain(String[] args){ QueueToStack queueToStack = new QueueToStack(); queueToStack.push(1); queueToStack.push(2); queueToStack.push(3); queueToStack.push(4); queueToStack.pop(); int data = queueToStack.top(); System.out.println(data); System.out.println(queueToStack.empty()); }
Queue<Integer> queueA = new LinkedList<>(); Queue<Integer> queueB = new LinkedList<>();
/** * Push element x onto stack. */ publicvoidpush(int x){ if (queueA.isEmpty() && !queueB.isEmpty()) { queueA.add(x); while (!queueB.isEmpty()){ int data = queueB.remove(); queueA.add(data); }
} elseif (!queueA.isEmpty() && queueB.isEmpty()) { queueB.add(x); while (!queueA.isEmpty()){ int data = queueA.remove(); queueB.add(data); }
/** * Removes the element on top of the stack and returns that element. */ publicintpop(){ if (queueA.isEmpty() && !queueB.isEmpty()) return queueB.remove(); return queueA.remove();
}
/** * Get the top element. */ publicinttop(){ if (queueA.isEmpty() && !queueB.isEmpty()) return queueB.peek(); return queueA.peek(); }
/** * Returns whether the stack is empty. */ publicbooleanempty(){ if (queueA.isEmpty() && queueB.isEmpty()) returntrue; returnfalse; } }