Advertisement
Guest User

Untitled

a guest
Sep 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. public class LinkedList<T> implements ListInterface<T> {
  2.  
  3. Node<T> head;
  4. int size;
  5. // constructor
  6. public class Node<T> {
  7. public T data;
  8. public Node<T> next;
  9. public Node (T data, Node<T> next) {
  10. this.data = data;
  11. this.next = next;
  12. }
  13. }
  14. //add
  15. public void add(T data, int index) {
  16. if (size == 0 || index == 0) { // if there isn't an existing list create one and set head position
  17. head = new Node<T>(data, head);
  18. }
  19. else { // loops the list starting from head, at an empty spot add the object
  20. Node<T> current = head;
  21. while(index > 1) { // increment pointer until desired index is reached
  22. current = current.next;
  23. index--;
  24. }
  25. current.next = new Node<T>(data, current.next);
  26. }
  27. size++;
  28. }
  29. // get
  30. public T get(int index) {
  31. Node<T> current = head;
  32. while(index > 0) {
  33. if (current == null) { // if nothing exists at this index, throw exception
  34. throw new ListException("Cannot get item/DNE.");
  35. }
  36. // increment pointer
  37. current = current.next;
  38. index--;
  39. }
  40. return current.data;
  41. }
  42. // remove
  43. public void remove(int index) {
  44. Node<T> current = head;
  45. if (current == null)// if there isn't an object in the index, throw exception
  46. throw new ListException("Cannot remove item/DNE.");
  47. if(index == 0) { // If you want to remove at the beginning, we need to reassign the head
  48. head = head.next;
  49. }
  50. else {
  51. while (index > 1) { // loop to the desired index
  52. current = current.next;
  53. index--;
  54. }
  55. // reassigns the index, removed item is detached and gets garbage collected.
  56. current.next = current.next.next;
  57. }
  58. size--;
  59. }
  60. // size
  61. public int size() {
  62. return size;
  63. }
  64. // Appends contents of list to a stringbuffer and returns them
  65. public String toString() {
  66. Node<T> node = head;
  67. StringBuffer str = new StringBuffer();
  68. while (node != null) {
  69. str.append(node.data.toString() + " ");
  70. node = node.next;
  71. }
  72. return str.toString();
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement