// Program to test solutions to problem #9 on the cse143 final, fall 2010. // Fill in your solution to reorder3, then compile and run the program import java.util.*; class LinkedIntList { public void reorder3() { // fill in your solution here } private ListNode front; // first value in the list // this is the sample solution public void reorder3_() { if (front != null && front.next != null) { ListNode temp = front; front = temp.next; temp.next = front.next; front.next = temp; ListNode current = temp.next; while (current != null && current.next != null && current.next.next != null) { temp = current.next; current.next = temp.next; temp.next = current.next.next; current.next.next = temp; current = temp.next; } } } // 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 FinalTest9 { public static void main(String[] args) { for (int i = 0; i <= 15; i++) test(i); } public static void test(int n) { LinkedIntList list1 = new LinkedIntList(); LinkedIntList list2 = new LinkedIntList(); for (int i = 1; i <= n; i++) { list1.add(i); list2.add(i); } boolean fail = false; System.out.println("list = " + list1); list1.reorder3_(); System.out.println("expected = " + list1); try { list2.reorder3(); } catch (RuntimeException e) { System.out.println(" threw " + e + " with list = " + list2); fail = true; } if (!fail && !list1.toString().equals(list2.toString())) { System.out.println("actual = " + list2); 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; } }