Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- GENERAL TASK DESCRIPTION
- Implement barebones (meaning - no getters/setters, or anything extraneous
- In task descriptions after data structure name the required interface (list of public methods) is in parentheses
- Use proper formatting. Implement each data structure in a separate class. For Node classes use inner classes.
- For brevity use primitive integer as value type (no generics).
- */
- // Task 1 - singly-linked list (add, get, remove) add(), get(i), remove(i), remove(O)
- // Task 2 - stack (push, pop)
- // Task 3 - queue (offer, poll)
- // Task 4 - flexible-size list (using arrays - think of ArrayList) - (add, get, remove, insert)
- class MyList {
- private Integer[] arr;
- private int capacity;
- private int size;
- MyList(int capacity) {
- arr = new Integer[capacity];
- this.capacity = capacity;
- }
- public void add(Integer value) {
- if (size == capacity) {
- expandArray();
- }
- arr[++size - 1] = value; // size++ does the job
- }
- public Integer get(int idx) {
- if (ind < 0 || ind >= size)
- throw new ArrayIndexOutOfBounds();
- return arr[idx];
- }
- public Integer remove(int idx) {
- if (idx < 0 || idx >= size)
- throw new ArrayIndexOutOfBoundsException();
- Integer value = arr[idx];
- System.arraycopy(arr, idx + 1, arr, idx, size - idx - 1);
- arr[size - 1] = null;
- // 1 2 3 4 5
- // 1 2 4 5 5
- size--;
- return value;
- }
- public void insert(int idx, Integer value) {
- if (ind < 0 || ind >= size)
- throw new ArrayIndexOutOfBounds();
- if (size == capacity) {
- expandArray();
- }
- System.arraycopy(arr, idx, arr, idx + 1, size - idx);
- arr[idx] = value;
- size++;
- }
- private void expandArray() {
- Integer[] newArr = new Integer[capacity + capacity];
- System.arraycopy(arr, 0, newArr, 0, size);
- arr = newArr;
- capacity += capacity;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement