// Program to test solutions to problem #3 on the cse143 midterm, fall 2012. // There is a different method for each subproblem. public class Test3 { public static void main(String[] args) { problem1(); problem2(); problem3(); } public static void problem1() { ListNode p = new ListNode(1, new ListNode(2)); ListNode q = null; System.out.println("before:"); System.out.println(text(p, "p")); System.out.println(text(q, "q")); // this is the sample solution--replace with your code to test q = p.next; p.next = null; System.out.println("after:"); String text1 = text(p, "p"); String text2 = text(q, "q"); System.out.println(text1); System.out.println(text2); if (text1.equals(" p->[1]") && text2.equals(" q->[2]")) System.out.println("PASSED"); else System.out.println("FAILED"); System.out.println(); } public static void problem2() { ListNode p = new ListNode(1, new ListNode(2)); ListNode q = null; System.out.println("before:"); System.out.println(text(p, "p")); System.out.println(text(q, "q")); // this is the sample solution--replace with your code to test q = p; p = p.next; q.next = null; System.out.println("after:"); String text1 = text(p, "p"); String text2 = text(q, "q"); System.out.println(text1); System.out.println(text2); if (text1.equals(" p->[2]") && text2.equals(" q->[1]")) System.out.println("PASSED"); else System.out.println("FAILED"); System.out.println(); } public static void problem3() { ListNode p = new ListNode(1, new ListNode(2, new ListNode(3))); ListNode q = new ListNode(4, new ListNode(5)); System.out.println("before:"); System.out.println(text(p, "p")); System.out.println(text(q, "q")); // this is the sample solution--replace with your code to test ListNode temp = q; q = p.next.next; p.next.next = temp.next; temp.next = p.next; p.next = temp; System.out.println("after:"); String text1 = text(p, "p"); String text2 = text(q, "q"); System.out.println(text1); System.out.println(text2); if (text1.equals(" p->[1]->[4]->[2]->[5]") && text2.equals(" q->[3]")) System.out.println("PASSED"); else System.out.println("FAILED"); System.out.println(); } public static String text(ListNode p, String text) { String result = " " + text; for (int i = 0; i < 5; i++) { if (p != null) { result += "->[" + p.data + "]"; p = p.next; } } if (p != null) result += "..."; return result; } } 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; } }