Advertisement
ibragimova_mariam

flexible-size list

Dec 14th, 2020
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. /*
  2. GENERAL TASK DESCRIPTION
  3.  
  4. Implement barebones (meaning - no getters/setters, or anything extraneous
  5. In task descriptions after data structure name the required interface (list of public methods) is in parentheses
  6. Use proper formatting. Implement each data structure in a separate class. For Node classes use inner classes.
  7. For brevity use primitive integer as value type (no generics).
  8. */
  9.  
  10. // Task 1 - singly-linked list (add, get, remove) add(), get(i), remove(i), remove(O)
  11.  
  12. // Task 2 - stack (push, pop)
  13.  
  14. // Task 3 - queue (offer, poll)
  15.  
  16. // Task 4 - flexible-size list (using arrays - think of ArrayList) - (add, get, remove, insert)
  17.  
  18.  
  19. class MyList {
  20.  
  21. private Integer[] arr;
  22. private int capacity;
  23. private int size;
  24.  
  25. MyList(int capacity) {
  26. arr = new Integer[capacity];
  27. this.capacity = capacity;
  28. }
  29.  
  30. public void add(Integer value) {
  31. if (size == capacity) {
  32. expandArray();
  33. }
  34. arr[++size - 1] = value; // size++ does the job
  35. }
  36.  
  37. public Integer get(int idx) {
  38. if (ind < 0 || ind >= size)
  39. throw new ArrayIndexOutOfBounds();
  40. return arr[idx];
  41. }
  42.  
  43. public Integer remove(int idx) {
  44. if (idx < 0 || idx >= size)
  45. throw new ArrayIndexOutOfBoundsException();
  46.  
  47. Integer value = arr[idx];
  48.  
  49. System.arraycopy(arr, idx + 1, arr, idx, size - idx - 1);
  50. arr[size - 1] = null;
  51.  
  52. // 1 2 3 4 5
  53. // 1 2 4 5 5
  54.  
  55. size--;
  56.  
  57. return value;
  58. }
  59.  
  60. public void insert(int idx, Integer value) {
  61. if (ind < 0 || ind >= size)
  62. throw new ArrayIndexOutOfBounds();
  63.  
  64. if (size == capacity) {
  65. expandArray();
  66. }
  67.  
  68. System.arraycopy(arr, idx, arr, idx + 1, size - idx);
  69.  
  70. arr[idx] = value;
  71. size++;
  72. }
  73.  
  74. private void expandArray() {
  75. Integer[] newArr = new Integer[capacity + capacity];
  76. System.arraycopy(arr, 0, newArr, 0, size);
  77. arr = newArr;
  78. capacity += capacity;
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement