001package algs13; 002import java.text.DecimalFormat; 003import stdlib.*; 004public class PlaygroundInsert { 005 private Node first; 006 static class Node { 007 public double item; 008 public Node next; 009 public Node (double item, Node next) { this.item = item; this.next = next; } 010 } 011 public void insert (double item) { 012 // TODO 013 } 014 015 public static void main (String[] args) { 016 //Trace.showObjectIdsRedundantly(true); 017 Trace.showBuiltInObjects(true); 018 Trace.drawStepsOfMethod ("insert"); 019 Trace.drawStepsOfMethod ("insertH"); 020 Trace.run (); 021 testInsert ("[ 11 21 31 41 51 ]", "11 21 41 51", 31); 022 //PlaygroundInsert list = of ("11 21 41 51"); 023 //list.insert(31); 024 Trace.draw (); 025 StdOut.println ("Finished tests"); 026 } 027 028 public static void main1 (String[] args) { 029 testInsert ("[ 11 21 31 41 51 ]", "11 21 41 51", 31); 030 testInsert ("[ 11 21 31 41 51 ]", "11 31 41 51", 21); 031 testInsert ("[ 11 21 31 41 51 ]", "11 21 31 51", 41); 032 testInsert ("[ 11 21 31 41 51 ]", "11 21 31 41", 51); 033 testInsert ("[ 11 ]", "", 11); 034 testInsert ("[ 11 21 31 41 51 ]", "21 31 41 51", 11); 035 StdOut.println ("Finished tests"); 036 } 037 038 /* ToString method to print */ 039 public String toString () { 040 // Use DecimalFormat #.### rather than String.format 0.3f to leave off trailing zeroes 041 DecimalFormat format = new DecimalFormat ("#.###"); 042 StringBuilder result = new StringBuilder ("[ "); 043 for (Node x = first; x != null; x = x.next) { 044 result.append (format.format (x.item)); 045 result.append (" "); 046 } 047 result.append ("]"); 048 return result.toString (); 049 } 050 051 /* Method to create lists */ 052 public static PlaygroundInsert from(String s) { 053 PlaygroundInsert result = new PlaygroundInsert (); 054 if ("".equals (s)) return result; 055 056 Node first = null; 057 String[] nums = s.split (" "); 058 for (int i = nums.length-1; i >= 0; i--) { 059 try { 060 double num = Double.parseDouble (nums[i]); 061 first = new Node (num, first); 062 } catch (NumberFormatException e) { 063 throw new IllegalArgumentException (String.format ("Bad argument \"%s\": could not parse \"%s\" as a double", s, nums[i])); 064 } 065 } 066 result.first = first; 067 return result; 068 } 069 070 private static void testInsert (String expected, String list, double item) { 071 PlaygroundInsert aList = PlaygroundInsert.from (list); 072 aList.insert (item); 073 String actual = aList.toString (); 074 if (! expected.equals (actual)) { 075 StdOut.format ("Failed [%s].insert(%f): Expecting (%s) Actual (%s)\n", list, item, expected, actual); 076 } 077 } 078}