Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active August 29, 2015 14:11
Show Gist options
  • Save rshepherd/5b72bbd9cbe57dda7828 to your computer and use it in GitHub Desktop.
Save rshepherd/5b72bbd9cbe57dda7828 to your computer and use it in GitHub Desktop.
Final review on data structures
import java.util.*;
// Let me know if you find any mistakes!!
public class FinalReview {
public static void main(String[] args) {
System.out.println("Question 1:");
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
System.out.println("Forward: " + list.toString());
System.out.println("Reverse: " + reverse(list).toString());
}
public static <T> List<T> reverse(List<T> list) {
Stack<T> stack = new Stack<>();
for(int i = 0 ; i < list.size() ; ++i) {
stack.push(list.get(i));
}
for(int i = 0 ; i < list.size() ; ++i) {
list.set(i, stack.pop());
}
return list;
}
// Question 2a:
// 42 returned
// 14 returned
// 2 returned
// 19 returned
// 5 returned
// Stack contains: 5 14
// Question 2b:
// 4 returned
// 8 returned
// 98 returned
// 15 returned
// Queue contains: 15, 5, 2
// Question 2c:
// An array is a good choice if you want your data structure to be bounded.
// A linked list is a more natural choice if you do not want bounds
// Question 2d:
// 4 * 3 * 2 * 1 = 24
// Question 2e:
// Same as they went in. 'D', 'C', 'B', 'A'
// Question 2f:
// Assuming it doesn't cause a null pointer exception, then it serves to delete a node out of the list.
// If you have n1 -> n2 -> n3, n1.next.next = n3
// by setting a pointer to n3 to n1.next, n2 is effectively deleted
// Question 2g:
// The node 't' gets inserted into the linked list. (draw it on paper and its relatively clear)
// Question 2h:
// An array, since you can reference any element in it by its offset from beginning.
// Moreover, if you want the 4th element, array[3] will fetch it.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment