// Program to test solutions to problem #3 on the cse143 midterm, spring 2011. // Fill in your solution to minGap, then compile and run the program import java.util.*; class LinkedIntList { public int minGap() { // fill in your solution here } private ListNode front; // first value in the list // this is the sample solution public int minGap2() { if (front == null || front.next == null) { return 0; } else { int min = front.next.data - front.data; ListNode current = front.next; while (current.next != null) { int gap = current.next.data - current.data; if (gap < min) { min = gap; } current = current.next; } return min; } } // post: constructs an empty list public LinkedIntList() { front = null; } // post: creates a comma-separated, bracketed version of the list public String toString() { if (front == null) return "[]"; else { String result = "[" + front.data; ListNode current = front.next; while (current != null) { result += ", " + current.data; current = current.next; } result += "]"; return result; } } // post: appends the given value to the end of the list public void add(int value) { if (front == null) front = new ListNode(value); else { ListNode current = front; while (current.next != null) current = current.next; current.next = new ListNode(value); } } } public class Test3 { public static void main(String[] args) { test(new int[] {}); test(new int[] {42}); test(new int[] {3, 3, 3}); test(new int[] {4, 5}); test(new int[] {0, 10, 15, 23, 45}); test(new int[] {1, 2, 2, 3, 3, 3}); test(new int[] {-8, -5, -5, 0, 17}); test(new int[] {42, 42, 42, 42, 42}); test(new int[] {1, 3, 6, 7, 12}); test(new int[] {3, 5, 11, 4, 8}); test(new int[] {5, 105, 206, 308, 411, 515, 620}); test(new int[] {-5, -105, -206, -308, -411, -515, -620}); test(new int[] {0, Integer.MAX_VALUE}); } public static void test(int[] data) { LinkedIntList list = new LinkedIntList(); for (int n : data) { list.add(n); } System.out.println("list = " + list); int gap1 = list.minGap2(); System.out.println("minGap = " + gap1); boolean fail = false; try { int gap2 = list.minGap(); if (gap1 != gap2) { fail = true; System.out.println("yours = " + gap2); } } catch (RuntimeException e) { System.out.println(" threw " + e); fail = true; } if (fail) System.out.println("failed"); else System.out.println("passed"); System.out.println(); } } class ListNode { public int data; // data stored in this node public ListNode next; // link to next node in the list // post: constructs a node with data 0 and null link public ListNode() { this(0, null); } // post: constructs a node with given data and null link public ListNode(int data) { this(data, null); } // post: constructs a node with given data and given link public ListNode(int data, ListNode next) { this.data = data; this.next = next; } }