
import java.awt.Font;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 *
 * @author Bill Kraynek
 */
public class SortedJavaLinkedList {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        LinkedList<String> stringList = new LinkedList<String>();
        try {
            Scanner fileScanner = new Scanner(new File("src/SingleLinkedListExample.java"));
            fileScanner.useDelimiter("[^a-zA-Z]+");
            while (fileScanner.hasNext()) {
                String aWord = fileScanner.next();
                sortedInsert(stringList,aWord);
            } // end while
        } catch (Exception e) {
            e.printStackTrace();
        } // end try/catch
        String out = "\t" + display(stringList);
        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();
        LinkedList<Integer> intList = new LinkedList<Integer>();
        for (int i = 0; i < 20; i++) {
            sortedInsert(intList,random.nextInt(1000));
        }// end for
        out = "\t" + display(intList);
        outArea.setText(out);
        JOptionPane.showMessageDialog(null, new JScrollPane(outArea));
    }

    static <T> String display(List<T> list) {
        String out = "";
        for (T x : list) {
            out += x + "\n\t";
        }
        return out;
    }

    static <T extends Comparable<T>>  void sortedInsert(List<T> list, T item) {
        ListIterator<T> itr = list.listIterator();
        boolean moreInList = true;
        while (moreInList = itr.hasNext()) {
            T nextWord = itr.next();
            if (item.compareTo(nextWord) < 0) {
                break;
            }
            if (item.equals(nextWord)) {
                return;
            }// end if
        }// end while
        // if not at the end of the List back up
        if (moreInList) {
            itr.previous();
        }
        itr.add(item);
    }
}

