How should I change in get method without calling getList() of Deque? [closed]
https://softwareengineering.stackexchange.com/questions/270988
-
07-10-2020 - |
Question
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<Integer> 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;
}
}
Thanks
~July
Solution
You can use recursion to remove index-1
elements from the beginning of the queue, store the the first element and then, as you are unwinding the recursion, put removed elements back on the queue:
public static int get(Deque queue, int index) throws Exception {
int tmp = queue.removeFirst();
try {
if (index == 0) {
return tmp;
} else {
return get(queue, index - 1);
}
} finally {
queue.addFirst(tmp);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with softwareengineering.stackexchange