Stacks:
Items stored in Last In First Out order, or in other words, the items are returned in the opposite order in which they were entered. Imagine a stack of plates at an all-you-can-eat buffet. The last plates put on the stack are the first ones that are taken by the customer.
Example:
Stack<Integer> buffet = new Stack<Integer>();
buffet.push(1); // stack is now [1]
buffet.push(2); // stack is now [1, 2]
buffet.push(3); // stack is now [1, 2, 3]
buffet.pop(); // returns the last item entered and removes it from the stack //3
buffet.peek(); // returns the last item entered but does not remove it from the stack //2
Queues:
Items stored in First In First Out, or in other words, items are returned in the order they are put in. Imagine a line, the first person in line is the first person that leaves the line.
Example:
Queue<Integer> line = new PriorityQueue<Integer>();
line.add(1); // queue is now [1]
line.add(2); // queue is now [1, 2]
line.add(3); // queue is now [1, 2, 3]
line.remove(); // returns the first item entered and removes it from the queue // 1
line.peek(); // returnsthe first item entered but does not remove it from the queue // 2
No comments:
Post a Comment