Lab 10: Queue
1. Write a generic queue class called MyQueue using LinkedList. Implement the following methods: a. public void enqueue(E o) b. public E dequeue() c. public E peek() d. public int getSize() e. public boolean isEmpty(); f. public String toString() public static void main(String[] args) { // TODO code application logic here MyQueue <String > fruitQ = new MyQueue <String >(); fruitQ.enqueue("Apple"); fruitQ.enqueue(" Orange"); fruitQ.enqueue("Grapes"); fruitQ.enqueue("Cherry"); fruitQ.enqueue("pear"); System.out.println(fruitQ);
System.out.println( fruitQ.peek()); fruitQ.dequeue(); System.out.println(fruitQ.isEmpty()); System.out.println(fruitQ.getSize()); }
}
public class MyQueue<E> { private LinkedList<E> list = new LinkedList<E>(); public void enqueue(E o) { list.add(o); } public E dequeue(){
E o = list.get(getSize() - 1); list.remove(getSize() - 1); return o ; } public E peek() { return list.get(getSize() - 1); } public int getSize() { return list.size(); }
public boolean isEmpty() { return list.isEmpty(); }
@Override public String toString() { return "queue: " + list.toString();
}
} public class fruitQ { public static void main(String[] args) { MyQueue <String > t = new MyQueue <String >(); t.enqueue("Apple"); t.enqueue(" Orange"); t.enqueue("Grapes"); t.enqueue("Cherry"); System.out.println(t.toString()); }
}
2. Write a test program that keeps the list of the following fruit items called fruitQ in the queue in the following order: Apple, Orange, Grapes, Cherry. Perform the following operations