fork(7) download
  1. class DataLinkedList {
  2. public static class Node {
  3. int data;
  4. Node nextNode;
  5.  
  6. public Node(int data) {
  7. this.data = data;
  8. this.nextNode = null;
  9. }
  10.  
  11. public int getData() {
  12. return this.data;
  13. }
  14. } // Node class
  15.  
  16. private Node head;
  17. private int size;
  18.  
  19. public DataLinkedList(){
  20. this.head = null;
  21. this.size = 0;
  22. }
  23.  
  24. public void add(int data) {
  25. Node node = new Node(data);
  26. if (head == null) {
  27. head = node;
  28. } else {
  29. Node currentNode = head;
  30. while(currentNode.nextNode != null) {
  31. currentNode = currentNode.nextNode;
  32. }
  33. currentNode.nextNode = node;
  34. }
  35. size++;
  36. }
  37.  
  38. public void sort() {
  39. if (size > 1) {
  40. boolean wasChanged;
  41.  
  42. do {
  43. Node current = head;
  44. Node previous = null;
  45. Node next = head.nextNode;
  46. wasChanged = false;
  47.  
  48. while ( next != null ) {
  49. if (current.data > next.data) {
  50. /*
  51.   // This is just a literal translation
  52.   // of bubble sort in an array
  53.   Node temp = currentNode;
  54.   currentNode = next;
  55.   next = temp;*/
  56. wasChanged = true;
  57.  
  58. if ( previous != null ) {
  59. Node sig = next.nextNode;
  60.  
  61. previous.nextNode = next;
  62. next.nextNode = current;
  63. current.nextNode = sig;
  64. } else {
  65. Node sig = next.nextNode;
  66.  
  67. head = next;
  68. next.nextNode = current;
  69. current.nextNode = sig;
  70. }
  71.  
  72. previous = next;
  73. next = current.nextNode;
  74. } else {
  75. previous = current;
  76. current = next;
  77. next = next.nextNode;
  78. }
  79. }
  80. } while( wasChanged );
  81. }
  82. }
  83.  
  84. public int listSize() {
  85. return size;
  86. }
  87.  
  88. public void printData() {
  89. Node currentNode = head;
  90.  
  91. System.out.print("[ ");
  92. while(currentNode != null) {
  93. int data = currentNode.getData();
  94. System.out.print(data + " ");
  95. currentNode = currentNode.nextNode;
  96. }
  97.  
  98. System.out.print(" ]");
  99. System.out.println();
  100. }
  101.  
  102. public boolean isEmpty() {
  103. return size == 0;
  104. }
  105. } // DataInterface class
  106.  
  107. class Ideone {
  108.  
  109. public static void main (String[]args) {
  110.  
  111. DataLinkedList dll = new DataLinkedList();
  112.  
  113. dll.add(8);
  114. dll.add(4);
  115. dll.add(3);
  116. dll.add(7);
  117. dll.add(6);
  118. dll.add(1);
  119.  
  120. dll.printData();
  121. dll.sort();
  122. dll.printData();
  123. System.out.println("List size: " + dll.listSize());
  124. }
  125. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
[ 8 4 3 7 6 1  ]
[ 1 3 4 6 7 8  ]
List size: 6