fork download
  1.  
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static LinkedList<String> list;
  11. public static void main(String[] args) {
  12. list = new LinkedList<String>();
  13. add("C3138");
  14. add("C3119");
  15. add("A1488");
  16. add("A1480");
  17. add("A1517");
  18. add("B1297");
  19. add("C2597");
  20. add("B1356");
  21. add("C9000");
  22. add("C3517");
  23. add("C3729");
  24. add("C1729");
  25. add("B1729");
  26.  
  27. printLL();
  28. }
  29. public static void add(String value) {
  30. // Integer value form the string passed into the method
  31. int valueInt = getInt(value);
  32.  
  33. // If linked list is empty, add value and return from method
  34. if (list.size() == 0) {
  35. list.add(value);
  36. return;
  37. }
  38.  
  39. // Compare this item to be added to the first item
  40. int firstNode = getInt(list.get(0));
  41. if (list.get(0).charAt(0) > value.charAt(0)
  42. || (list.get(0).charAt(0) == value.charAt(0) && firstNode > valueInt)){
  43. list.add(0, value);
  44. return;
  45. }
  46.  
  47. // Compare this item to the last item
  48. int lastNode = getInt(list.get(list.size() - 1));
  49. if (list.get(list.size() - 1).charAt(0) < value.charAt(0) ||
  50. (list.get(list.size() - 1).charAt(0) == value.charAt(0) && lastNode < valueInt)) {
  51. list.add(list.size(), value);
  52. return;
  53. }
  54. // add the inbetween items
  55.  
  56. int i = 1;
  57. int tempInt = getInt(list.get(i));
  58. while (i < list.size() && ( list.get(i).charAt(0) < value.charAt(0)
  59. || ((list.get(i).charAt(0) == value.charAt(0)) && (valueInt > tempInt)))) {
  60. i++;
  61. tempInt = getInt(list.get(i));
  62. }
  63. list.add(i, value);
  64.  
  65.  
  66.  
  67. }
  68. public static int getInt(String item) {
  69. return Integer.parseInt(item.replaceAll("\\D", ""));
  70. }
  71.  
  72. public static void printLL() {
  73. for(int i = 0; i < list.size(); i++) {
  74. System.out.print(list.get(i) + " ");
  75. }
  76. System.out.println("");
  77. }
  78. }
Success #stdin #stdout 0.1s 320320KB
stdin
Standard input is empty
stdout
A1480 A1488 A1517 B1297 B1356 B1729 C1729 C2597 C3119 C3138 C3517 C3729 C9000