import java.awt.Font; import java.io.File; import java.util.Random; import java.util.Scanner; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author Bill Kraynek */ public class SortedSingleLinkedListExample { /** * @param args the command line arguments */ public static void main(String[] args) { Node stringHeader = new Node<>(); try { Scanner fileScanner = new Scanner(new File("src/SortedSingleLinkedListExample.java")); fileScanner.useDelimiter("[^a-zA-Z]+"); while (fileScanner.hasNext()) { String aWord = fileScanner.next(); //sortedInsert(stringHeader, aWord); Node p = stringHeader; while( p.next != null ) { if( aWord.compareTo(p.next.data) <= 0) break; p = p.next; }// end while if( p.next == null || !aWord.equals(p.next.data) ) p.next = new Node<>(aWord,p.next); } } catch (Exception e) { e.printStackTrace(); ; } // end try/catch String out = "\t" + display(stringHeader); JTextArea outArea = new JTextArea(25, 40); outArea.setFont(new Font(Font.MONOSPACED, Font.BOLD, 15)); outArea.setText(out); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); Random random = new Random(); Node intHeader = new Node<>(); for (int i = 0; i < 20; i++) { sortedInsert(intHeader, random.nextInt(1000)); } out = "\t" + display(intHeader); out += "\n\tSum of ints\n\t" + sum(intHeader) + "\n\tMax of ints\n\t" + max(intHeader); outArea.setText(out); JOptionPane.showMessageDialog(null, new JScrollPane(outArea)); } // end main static String display(Node list) { if (list.next == null) { return ""; } return list.next.data + "\n\t" + display(list.next); } static int sum(Node list) { if (list.next == null) { return 0; } return list.next.data + sum(list.next); } static int max(Node list) { if (list.next.next == null) { return list.next.data; } int max = max(list.next); if (max < list.next.data) { return list.next.data; } return max; } static > void sortedInsert(Node list, T item) { if (list.next == null) { list.next = new Node(item); return; } if (item.compareTo(list.next.data) < 0) { list.next = new Node(item, list.next); return; } if (item.equals(list.next.data)) { return; } sortedInsert(list.next, item); } static class Node { T data; Node next; Node() { } Node(T data) { this.data = data; } // end Node(T data, Node next) { this.data = data; this.next = next; } // end public String toString() { return data + ""; } // end toString } // end Node }