What will be printed when the following code executes?
Stack<String> stack = new AStack<>();
Queue<String> queue = new AQueue<>();
stack.push("A");
stack.push("B");
stack.push("C");
stack.pop();
stack.push("D");
while (!stack.isEmpty()) {
queue.enqueue(stack.pop());
}
while (!queue.isEmpty()) {
System.out.print(queue.dequeue());
}
Our texbook’s LQueue class maintains both a front and rear
reference. Which of these corresponds to the head of the list? Which
of these corresponds to the tail of the list? (The answer is not
arbitrary. Only one of the two alternatives can be implemented
efficiently.)
Consider the following partial implementation of a circular-array-based queue:
|
Draw the state of the array at each of the indicated points below: |
Analyze each of the methods below according to the instructions in the
Javadoc comments. In each case you will be comparing the performance of
java.util.ArrayList with java.util.LinkedList. Recall that
java.util.LinkedList is implemented using a doubly-linked list that
maintains both a head and tail reference.
/*
* What is the big-Theta running time of this method, assuming that list is
*
*
* an ArrayList:
*
*
* a LinkedList:
*
*
*/
public static int sumByIndex(List<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
return sum;
}
/*
* What is the big-Theta running time of this method, assuming that list is
*
*
* an ArrayList:
*
*
* a LinkedList:
*
*
*/
public static int sumWithIterator(List<Integer> list) {
int sum = 0;
for (int curValue : list) {
sum += curValue;
}
return sum;
}
/*
* What is the big-Theta running time of this method, assuming that toList
* is initially empty, and that both lists are of type
*
*
* ArrayList:
*
*
* LinkedList:
*
*
*/
public static void copy(List<Integer> fromList,
List<Integer> toList) {
for (int item : fromList) {
toList.add(item);
}
}/*
* What is the big-Theta running time of this method, assuming that toList
* is initially empty, and that both lists are of type
*
*
* ArrayList:
*
*
* LinkedList:
*
*
*/
public static void copyReverseA(List<Integer> fromList,
List<Integer> toList) {
for (int item : fromList) {
toList.add(0, item);
}
}/*
* What is the big-Theta running time of this method, assuming that toList
* is initially empty, and that both lists are of type
*
*
* ArrayList:
*
*
* LinkedList:
*
*
*/
public static void copyReverseB(List<Integer> fromList,
List<Integer> toList) {
int value;
for (int i = fromList.size() - 1; i >= 0; i--) {
value = fromList.get(i);
toList.add(value);
}
}