Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. package opgave1;
  2.  
  3. public class SingleLinked {
  4. private Node<String> first;
  5.  
  6. public SingleLinked() {
  7. this.first = null;
  8. }
  9.  
  10. private static class Node<T> {
  11. private T data;
  12. private Node<T> next;
  13.  
  14. public Node(T data) {
  15. this.data = data;
  16. this.next = null;
  17. }
  18. }
  19.  
  20. /**
  21. * Adds the element to the list. The list is still sorted after the element is
  22. * added.
  23. */
  24. public void add(String element) {
  25. Node<String> newNode = new Node<>(element);
  26.  
  27. if (this.first == null || this.first.data.compareTo(element) >= 0) {
  28. newNode.next = this.first;
  29. this.first = newNode;
  30. } else {
  31. Node<String> current = this.first;
  32. while (current.next != null && current.next.data.compareTo(element) < 0) {
  33. current = current.next;
  34. }
  35. newNode.next = current.next;
  36. current.next = newNode;
  37. }
  38. }
  39.  
  40. /**
  41. * Removes the first instance of the element from the list. The list is still
  42. * sorted after the element is removed. Returns true, if the element was
  43. * removed, otherwise false.
  44. */
  45. public boolean remove(String element) {
  46. if (first == null) {
  47. return false;
  48. }
  49. if (first.data.equals(element)) {
  50. first = first.next;
  51. return true;
  52. }
  53. Node<String> n = first;
  54. while (n.next != null) {
  55. if (n.next.data.equals(element)) {
  56. n.next = n.next.next;
  57. return true;
  58. }
  59. n = n.next;
  60. }
  61.  
  62. return false;
  63. }
  64.  
  65. /**
  66. * Prints all elements in alphabetical order.
  67. */
  68. public void printElements() {
  69. Node<String> n = first;
  70. while (n != null) {
  71. System.out.println(n.data);
  72.  
  73. n = n.next;
  74. }
  75. }
  76.  
  77. /**
  78. * Returns the count of elements in the list.
  79. */
  80. public int count() {
  81. if (first == null) {
  82. return 0;
  83. }
  84. int count = 1;
  85. Node<String> n = first;
  86. while (n.next != null) {
  87. n = n.next;
  88. count++;
  89. }
  90.  
  91. return count;
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement