package CK.IA;

import java.util.LinkedList;

@SuppressWarnings("unchecked")
/*
 * An LinkedList storing order in it's Comparable elements.
 */
public class OrderedLinkedList extends LinkedList {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5341231957600892198L;

	public static void main(String[] args) {
		OrderedLinkedList l = new OrderedLinkedList();
		l.add((int) (Math.random() * 100));
		l.add((int) (Math.random() * 100));
		l.add((int) (Math.random() * 100));
		l.add((int) (Math.random() * 100));
		l.add((int) (Math.random() * 100));
		l.add((int) (Math.random() * 100));
		l.add((int) 10);
		l.add((int) 10);
	}

	public boolean add(Comparable e) {
		if (super.size() == 0) {
			// empty list, just add
			return super.add(e);
		} else {
			// search for an element greater than this one
			for (int index = 0; index < super.size(); index++) {
				Comparable node = (Comparable) super.get(index);
				int comp = e.compareTo(node);
				if (comp < 0) {
					super.add(index, e);
					return true;
				}
			}
			// if we didn't found an element greater than this it's because this one is the greater, so add it
			// to the end
			// of the list
			super.addLast(e);
			return true;
		}
	}

}
