Question
The code below about RandomizedQueue when I test it it jsut show the last element add. Any help to fix that to show all element
The code below about RandomizedQueue when I test it it jsut show the last element add. Any help to fix that to show all element that "enqueue" in RandomizedQueue
public class RandomizedQueue
public static void main(String[] args) {
}
public int count=0;
private Item[]list;
@Override
public Iterator
// TODO Auto-generated method stub
return new RandomizedQueueIterator<>();
}
// construct an empty randomized
public RandomizedQueue() {
list=(Item[])new Object[1];
}
// is the randomized queue empty?
public boolean isEmpty() {
return count==0;
}
// return the number of items on the randomized queue
public int size() {
return count;
}
// add the item
public void enqueue(Item item) {
if (item == null)
throw new NullPointerException();
if (list.length <= count)
resize(count * 2);
list[count++] = item;
}
private void resize(int i) {
// TODO Auto-generated method stub
Item[] temp = (Item[]) new Object[i];
for (int j = 0; i < list.length; i++) {
temp[j] = list[j];
}
list = temp;
}
// remove and return a random item
public Item dequeue() {
if (count == 0)
throw new NoSuchElementException();
int i = StdRandom.uniform(count);
Item x = list[i];
list[i] = list[count - 1];
list[count - 1] = null;
count = count - 1;
return x;
}
// return a random item (but do not remove it)
public Item sample() {
if (count == 0)
throw new NoSuchElementException();
int randomItemIndex = StdRandom.uniform(count);
return list[randomItemIndex];
}
private class RandomizedQueueIterator
private int value;
private int[]list_value= new int[count];
@Override
public boolean hasNext() {
return value } @Override public Item next() { if(!hasNext()) throw new NoSuchElementException(); return (Item) list[list_value[value++]]; } } } Here the test: public class RandomizedQueueTest { public static void main(String[] args) { RandomizedQueue System.out.println("Test Deque"); rq.enqueue("A"); rq.enqueue("B"); rq.enqueue("C"); assert rq.size() == 3; for (int i = 0; i < 3; i++) { System.out.println(rq.dequeue()); } } } Return: Test Deque C null null
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started