sorting - Inserting into sorted linked list - Java -


i need maintain sorted data structure items can deleted , added. decided choose linked list. each data item contains letter , numbers such these: a1480, a1488, b1297, c3119 these need maintained in order. have written code first finds position sorted linked list new item needs added , adds item correct position, therefore maintaining sorted linked list. works items misplaced , not sure how fix code. know there wrong last loop not sure is.

    public static void main(string[] args) {     list = new linkedlist<string>();     add("c3138");     add("c3119");     add("a1488");     add("a1480");     add("a1517");     add("b1297");     add("c2597");     add("b1356");     add("c9000");     add("c3517");     add("c3729");     add("c1729");     add("b1729"); }  public static void add(string value) {     // integer value form string passed method     int valueint = getint(value);      // if linked list empty, add value , return method     if (list.size() == 0) {         list.add(value);         return;     }      // compare item added first item     int firstnode = getint(list.get(0));     if (list.get(0).charat(0) > value.charat(0)              || (list.get(0).charat(0) == value.charat(0) && firstnode > valueint)){         list.add(0, value);         return;     }      // compare item last item     int lastnode = getint(list.get(list.size() - 1));     if (list.get(list.size() - 1).charat(0) < value.charat(0) ||              (list.get(list.size() - 1).charat(0) == value.charat(0) && lastnode < valueint)) {         list.add(list.size(), value);         return;     }     // add inbetween items     int = 1;     int tempint = getint(list.get(i));     while ((list.get(i).charat(0) < value.charat(0)             || ((list.get(i).charat(0) == value.charat(0)) && (valueint < tempint)) && < list.size())) {          tempint = getint(list.get(i));         i++;     }     list.add(i, value); }   public static int getint(string item) {     return integer.parseint(item.replaceall("\\d", "")); } 

this code below gives me output of:

[a1480, a1517, a1488, b1729, b1297, b1356, c1729, c3729, c3517, c2597, c3119, c3138, c9000]

and can see values in between start , finish misplaced start , end values correct. please

take @ why there no sortedlist in java?

if values unique, can use treeset. generally, if want sorted collection, don't want start linkedlist.


Comments