
22c:021 Computer Science II: Data Structures Name:
Midterm Exam, Fall 2010
Open books and notes; no computers
1. [25 points] FindTriples returns true if there are three equal integers in the array A.
public static boolean FindTriples( int[] A ) {
for (int i = 0; i < A.length; i++)
for (int j = i+1; j < A.length; j++)
for (int k = j+1; k < A.length; k++)
if (A[i] == A[j] && A[i] == A[k] && A[j] == A[k]) return true;
return false;
}
(a) What is the running time of this method?
O(n
3
)
(b) Describe a more efficient algorithm than the one above and give its running time. No code is
needed in your answer.
We may first sort the array using mergesort and then check if A[i-2] == A[i] for i from 2 to
A.length. Sorting takes O(n lg n) and the checking takes O(n). The total time is O(n lg n).
2. [25 points] Suppose the class Link is used to define a linked list:
class Link { public long data;
Link next;
public Link (long d) { data = d; }}
class LinkList {
private Link first; …
public LinkList reverse() { … }
… }
Please complete the method reverse that reverses a linked list without destroying the original list.
Syntax errors are allowed. What is the running time of your implementation?
public LinkList reverse() {
Link current = this.first;
LinkList rev = new LinkList();
while (current != null) {
Link node = new Link(current.data);
node.next = rev.first;
rev.first = node;
current = current.next;
}
return rev;
}
The running time is O(n).