Implement Queue/Stack
Queue: First-in-first-out
// Initialize a queue.
Queue<Integer> q = new LinkedList();
// Get the first element - return null if queue is empty.
q.peek();
// Push new element.
q.offer(5);
// Pop an element.
q.poll();
Stack: Last-in-fist-out
// Initialize a stack.
Stack<Integer> s = new Stack<>();
// Push new element.
s.push(5);
// Check if stack is empty.
if (s.empty() == true) {
System.out.println("Stack is empty!");
return;
}
// Pop an element.
s.pop();
// Get the top element.
s.peek();
// Get the size of the stack.
s.size();
Last updated