
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<String> stringHeader = new Node<String>();
        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);
            }
        } 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<Integer> intHeader = new Node<Integer>();
        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 <T> String display(Node<T> list) {
        if( list.next == null ) return "";
        return list.next.data + "\n\t" + display(list.next);
    }

    static int sum(Node<Integer> list) {
        if( list.next == null ) return 0;
        return list.next.data + sum(list.next);
    }

    static int max(Node<Integer> 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 <T extends Comparable<T>> void sortedInsert(Node<T> list, T item ) {
        if( list.next == null ) {
            list.next = new Node<T>(item);
            return;
        }
        if( item.compareTo(list.next.data) < 0 ) {
            list.next = new Node<T>(item,list.next);
            return;
        }
        if( item.equals(list.next.data)) return;
        sortedInsert(list.next,item);
    }

}

class Node<T> {
    T data;
    Node<T> next;
    Node() {
    }
    Node(T data) {
        this.data = data;
    } // end
    Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    } // end
    public String toString() {
        return data + "";
    } // end toString
} // end Node


