Sarvesh
BAN USER- -4of 4 votes
Answersin this i have to improve the enqueue function
- Sarvesh in United States
enqueue returns the queue after adding the element but the original queue is not to be changed
and same is for dequeue function
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
public class PersistentQueue<E>{
private List<E> queue;
public PersistantQueue<E>(){
queue=new ArrayList<E>();
}
private PersistentQueue(List<E> queue){
this.queue=queue;
}
public PersistantQueue<E> enqueue(E e){
/*
Returns the queue that adds an item into tail of this queue without modifying this queue ( how to return without cloning ??)
*/
if(e==null){
throw new IllegalArgumentException();
}
List<E> clone = new ArrayList<E>(queue);
clone.add(e);
return new PersistantQueue<E>(clone);
}
public PersistantQueue<E> dequeue(){
/*
Returns the queue that removes the object at the head of this queue without modifying this queue ( here also how to do instead of clone as it it slow ??)
*/
if(queue.isEmpty()){
throw new NoSuchElementException();
}
List<E> clone = new ArrayList<E>(queue);
clone.remove(0);
return new PersistantQueue<E>(clone);
}
public E peek(){
if(queue.isEmpty()){
throw new NoSuchElementException();
}
return queue.get(0);
}
public int size(){
return queue.size();
}
}| Report Duplicate | Flag | PURGE
Data Structures