001package algs13; 002import java.text.DecimalFormat; 003import stdlib.*; 004public class PlaygroundWithNonStaticNode { 005 private Node first; 006 class Node { 007 public double item; 008 public Node next; 009 public Node (double item, Node next) { 010 this.item = item; 011 this.next = next; 012 } 013 } 014 015 public static void main (String[] args) { 016 Trace.showBuiltInObjects(true); 017 Trace.run (); 018 PlaygroundWithNonStaticNode list1 = PlaygroundWithNonStaticNode.from ("5 11 5 5"); 019 PlaygroundWithNonStaticNode list2 = PlaygroundWithNonStaticNode.from ("24 35 67"); 020 Trace.draw(); 021 } 022 023 /* A silly method to show list creation */ 024 public PlaygroundWithNonStaticNode example(int i) { 025 Node x1 = new Node (i+10, null); 026 Node x2 = new Node (i+20, null); 027 Node x3 = new Node (i+30, null); 028 Node x4 = new Node (i+40, null); 029 PlaygroundWithNonStaticNode result = new PlaygroundWithNonStaticNode (); 030 result.first = x1; 031 x1.next = x2; 032 x2.next = x3; 033 x3.next = x4; 034 return result; 035 } 036 037 /* ToString method to print */ 038 public String toString () { 039 // Use DecimalFormat #.### rather than String.format 0.3f to leave off trailing zeroes 040 DecimalFormat format = new DecimalFormat ("#.###"); 041 StringBuilder result = new StringBuilder ("[ "); 042 for (Node x = first; x != null; x = x.next) { 043 result.append (format.format (x.item)); 044 result.append (" "); 045 } 046 result.append ("]"); 047 return result.toString (); 048 } 049 050 /* Method to create lists */ 051 public static PlaygroundWithNonStaticNode from(String s) { 052 PlaygroundWithNonStaticNode result = new PlaygroundWithNonStaticNode (); 053 if ("".equals (s)) return result; 054 055 Node first = null; 056 String[] nums = s.split (" "); 057 for (int i = nums.length-1; i >= 0; i--) { 058 try { 059 double num = Double.parseDouble (nums[i]); 060 first = result.new Node (num, first); 061 } catch (NumberFormatException e) { 062 throw new IllegalArgumentException (String.format ("Bad argument \"%s\": could not parse \"%s\" as a double", s, nums[i])); 063 } 064 } 065 result.first = first; 066 return result; 067 } 068 069}