Quiz 04 sample questions and answers
Here are examples of the kinds of questions you may be asked:
-
Write a method static
<K, V> void addToMultiMap(Map<K, List<V>> map, K key, V value)
.addToMultiMap
must addvalue
to the end of the list associated with the givenkey
, creating the list if necessary.For full credit, your method must include generic types, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume
Map
,List
,HashMap
, andArrayList
are correctly imported fromjava.util
. You may not import other classes.For the solution, see Lecture 18.
-
Draw a undirected graph with four vertices. The graph must be connected but not complete.
Any connected undirected graph with four vertices and fewer than six edges is correct.
-
Some graphs are dense (that is, most possible edges are present) and some are sparse (most possible edges are absent). For a sparse graph, which representation uses more space on average, an adjacency list or an adjacency matrix?
An adjacency matrix.
-
Is depth-first search guaranteed to find a path to a goal in a finite graph? Is the path it finds guaranteed to be (one of) the shortest such paths?
Yes. No.
-
Suppose you have an empty stack of integers, and on that stack you execute the following operations:
- push 1
- push 2
- pop
- push 1
- push 3
- push 4
- pop
- push 1
Show the contents of the stack. Clearly indicate the top of the stack.
Starting at the top: 1 3 1 1
-
Suppose we have an array-based implementation of a
Stack<E>
.It has two instance variables. The first is a generic array
E[] array
, which contains the elements of the stack, if any, with the top of the stack in the rightmost cell (that is, the cell with the largest index). For example, if the stack holds two values,E[0]
holds one, andE[1]
holds the other, and the value inE[1]
is at the top of the stack. The other isint top
, which contains the index of the current top of the stack, or-1
if the stack is empty.Write a push method with the signature
public void push(E e) throws StackOverflowException
. You can assume the existence of anisFull
method andStackOverflowException
class.For the solution, see Lecture 20.