I got sucked with this FIFO java problem Hope someone could
I got sucked with this FIFO java problem.
Hope someone could help me get started.
Thank you very much!
Exercise #4 Queueing Problem (20pts) In data structures, a queue is a data structure that is \"first in, first out\". It contains two methods enqueue adds an item to the queue dequeue removes an item from the queue For this assignment you are going to implement a variation on this called a priority queue, where an integer corresponding to the priority is passed into the enqueue method upon invocation. As an example, we can have three successive calls to add items to the queue: q-enqueue(\"X\", 10) q enqueue(\"Y\", 1) q-enqueue(\"Z\", 3) Invoking dequeue on the object will then remove the item \"X\" from the queue, since it has the highest priority. Asecond invocation of the method returns \"Z\" while the third invocation returns \"Y\". Use an ArrayList as a representation of the queue. Include a main method which demonstrates successive adds and removals from your queue.Solution
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Surya
*/
import java.util.*;
public class PriorityQueue {
//declaring arraylist variables..
ArrayList<String> Q = new ArrayList<String>();//for storing values..(data)
ArrayList<String> priority = new ArrayList<String>();//for priority..
void enqueue(String s,int pr)//method to add elements to queue
{
int l=this.Q.size();//getting size of queue.
int i=0,pp;
String p = Integer.toString(pr);
for(i=0;i<l;i++)
{
pp = Integer.parseInt(priority.get(i));
if(pp>pr) {//calculating correct position to insert
// System.out.println(\"greater\ \");
break;
}
}
Q.add(i,s);//adding to queue.. in sorted order of priority...
priority.add(i,p);
}
String dequeue()
{
int l=this.Q.size();
//removing highest priority element
priority.remove(l-1);
String s = Q.get(l-1);
Q.remove(l-1);
return s;//returning element..
}
public static void main(String argv[])
{
//testing code..
PriorityQueue q = new PriorityQueue();
q.enqueue(\"X\",10);
q.enqueue(\"Y\",1);
q.enqueue(\"Z\",3);
System.out.println(q.dequeue());
System.out.println(q.dequeue());
System.out.println(q.dequeue());
}
}
output:-
X
Z
Y

