Language: Java
Topic: Deques
Using the following variables/class:
public class ArrayDeque<T> {
/**
* The initial capacity of the ArrayDeque.
*
* DO NOT MODIFY THIS VARIABLE.
*/
public static final int INITIAL_CAPACITY = 11;
// Do not add new instance variables or modify existing
ones.
private T[] backingArray;
private int front;
private int size;
Q1: write a method called "public void
addLast(T data)" which adds an element to the back of a
Deque. If sufficient space is not available in the backing array,
resize it to double the current capacity. When resizing, copy
elements to the beginning of the new array and reset front to 0.
Must be amortized O(1).
* @param data the data to add to the back of the deque
* @throws java.lang.IllegalArgumentException if data is null
public class ArrayDeque<T> {
public static final int INITIAL_CAPACITY = 11;
private T[] backingArray;
private int front;
private int size;
public void addLast(T data) throws IllegalArgumentException{
int [] newarray;
try{
if (front>=(size-1)){
newarray=new int[size*2];
System.arraycopy(backingArray,0,newarray,0,size);
size=size*2;
front=0;
}
else
{
backingArray[front]=data;
front++;
}
}
catch(IllegalArgumentException e){
System.out.println("The data is null");
}
}
}
Get Answers For Free
Most questions answered within 1 hours.