Sunday, June 19, 2016

DS Basics : Java Collections to Implement Stack and Queue

Hi folks ,
 
This is a very basic java lesson to how understand how we can best implement  a stack and a queue using Java Collections .
 
Stack - A stack is a data structure used to store a collection of objects. When an object is pushed to a stack, it is placed on the top of all previously entered items. When an item is popped off , it is removed from the top of the stack. It's a LIFO data structure.
 
Queue - Queue is also a linear data structure, in which the first element is inserted from one end called REAR(also called tail), and the deletion of exisiting element takes place from the other end called as FRONT(also called head). This makes queue as FIFO data structure, which means that element inserted first will also be removed first.
 
Let's use collections to implement a stack and a queue.
 
In this lesson we will be using Java's Deque interface and ArrayDeque implementation  to implement stack as well as queue.
 
The methods used will be :
 
push() | addFirst() -> Adds elements to the top of the stack .
pop() | removeFirst() -> Removes elements from the top of the stack.
 
add() |  addLast() -> Adds elements to the end of the queue.
remove() | removeFirst() -> Removes elements from the head of the queue.
 
Let's write a quick small program .

package arraydeq;
import java.util.ArrayDeque;
import java.util.Deque;

public class ArrayDeqStack {
private Deque<Integer> stk = new ArrayDeque<Integer>();
 // We could have also used the stack class but the arraydeque is 
 // likely to be faster than Stack when used as a stack, and faster
 // than theLinkedList when used as a queue.  

public void stack() {
  stk.push(1);
  stk.push(2);
  stk.addFirst(3);
  stk.push(4);
  stk.push(5);
  System.out.println(stk);  // [5, 4, 3, 2, 1]
  System.out.println(stk.pop()); //5
  System.out.println(stk.removeFirst()); //4
  System.out.println(stk.pop()); //3
  System.out.println(stk.pop()); //2
  System.out.println(stk.pop()); //1
}


public void queue() {
  stk.add(1);
  stk.add(2);
  stk.addLast(3);
  stk.add(4);
  stk.add(5);
  System.out.println(stk); // [1, 2, 3, 4, 5]
  System.out.println(stk.remove()); //1
  System.out.println(stk.remove()); //2
  System.out.println(stk.remove()); //3
  System.out.println(stk.removeFirst()); //4
  System.out.println(stk.remove()); //5
 }
}

 
That's all folks , Happy Learning .

No comments:

Post a Comment