samedi 24 janvier 2015

If I don't have getList() in Deque, how should I change in get method to return correctly?


import java.util.List; import java.util.ArrayList;


public class Test {



/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Deque queue = new Deque();

int random = (int)(Math.random() * 100);

queue.addLast(10);
queue.addLast(20);
queue.addLast(random);
queue.addLast(40);
queue.addLast(50);

for(int i = 0; i < 2; i++) {

assertTrue(get(queue, 0) == 10);
assertTrue(get(queue, 1) == 20);
assertTrue(get(queue, 2) == random);
assertTrue(get(queue, 4) == 50);
assertTrue(get(queue, 3) == 40);

try {
System.out.println(get(queue, 5));
assertTrue(false);
} catch(Exception e) {
assertTrue(true);
}
}
}

public static void assertTrue(boolean v) {
if(!v) {
Thread.dumpStack();
System.exit(0);
}
}


public static int get(Deque queue, int index) throws Exception
{
// 1) Only fill in your code in this method
// 2) Do not modify anything else
// 3) Use of 'new' keyword is not allowed
// 4) Do not use reflection
// 5) Do not use string concatenation

return queue.getList().get(index);
}


}


class Deque { private List items;



public Deque() {
items = new ArrayList<Integer>();
}

public void addFirst(int item) {
items.add(0, item);
}

public void addLast(int item) {
items.add(item);
}

public int removeFirst() {
if(isEmpty()) throw new RuntimeException();
return items.remove(0);
}

public int removeLast() {
if(isEmpty()) throw new RuntimeException();
return items.remove(items.size() - 1);
}

public boolean isEmpty() {
return items.size() == 0;
}

public List<Integer> getList()
{
return items;
}


}


// End


Thanks ~July





Aucun commentaire:

Enregistrer un commentaire