InterviewSolution
Saved Bookmarks
| 1. |
When to use the Queue and Stack? What is the possible use case? |
|
Answer» Stack and Queue work on the principal of First in Last Out and First in First out. The best use case of Queue is in the MESSAGING SERVICES, where we implement the messaging container, which allows one message to get input and another message get output from the queue. The queue has the ability to also act as a buffer to store the elements for the temporary time. Whereas Stack best use is to perform prefix, POSTFIX and infix operation in the Tree. Below is the code example of Stack: import java.util.Stack; public class StackExample { public static void main(String a[]){ Stack<Integer> stack = new Stack<>(); System.out.println("Empty stack : " + stack); // Checking whether the stack is empty? System.out.println("Empty stack : " + stack.isEmpty()); // Exception in THREAD "main" java.util.EmptyStackException // Adding the elements in the queue stack.push(1001); stack.push(1002); stack.push(1003); stack.push(1004); System.out.println("Non-Empty stack : " + stack); // Getting the elements from the queue System.out.println("Non-Empty stack: Pop Operation : " + stack.pop()); System.out.println("Non-Empty stack : After Pop Operation : " + stack); // Checking whether the elements in the queue. System.out.println("Non-Empty stack : search() Operation : " + stack.search(1002)); System.out.println("Non-Empty stack : " + stack.isEmpty()); } }Below is the code example of Queue: import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> queue = new LinkedList<>(); // Adds elements {0, 1, 2, 3, 4} to queue for (int i=0; i<5; i++) queue.add(i); // DISPLAY contents of the queue. System.out.println("Elements of queue-"+q); // To remove the head of queue. int removedele = queue.remove(); System.out.println("removed element-" + removedele); System.out.println(queue); // To view the head of queue int head = queue.peek(); System.out.println("head of queue-" + head); // Rest all methods of collection interface, // Like size and contains can be used with this // implementation. int size = queue.size(); System.out.println("Size of queue-" + size); } } |
|