Lecture 02: List Array Implementation
Overview:
- List ADT
- SimpleList interface
- Array Imp
- Linked List Imp
- Comparison of Imps
- Other ADTs: Stack, Queue, Deque
Logistics:
- TA session: M, W 7-9pm A131 or by zoom
- Assignment 1 due Sep 14
I. List ADT (lec01)
The state of a list is a sequence of n elements. S: x~0~, x~1~ … x~i-1~, x~i~ … x~n-1~ [n elements] Operations:
size()
- return num of elementsisEmpty()
- return (n==0)get(i)
- return \(x_i\) (0 ≤ i ≤ n-1)set(i, y)
- update state to \(x_0, x_1 \ldots x_{i-1}, y, x_{i+1} \ldots x_{n-1}\) (0 ≤ i ≤ n-1)add(i, y)
- update state to \(x_0, x_1 \ldots x_{i-1}, y, x_{i} \ldots x_{n-1}\) [new size n+1]remove(i)
- update state to \(x_0, x_1 \ldots x_{i-1}, x_{i+1} \ldots x_{n-1}\) [new size n-1]
Notice: after add & remove, the subscript no longer agree with the original index.
II. Example SimpleList interface
Java interface - specifies required functionality of an implementation (specify WHAT but not HOW) comments - specifies interpretation of operations parameterized data type E (see prof’s code).
III. Array Implmentation
1
2
3
Object[] contents = new Object [10]; // create fixed sized array
contents[3] // access item @ idx 3
contents[3] = value; // sets value of item @ idx 3
Store elements of list in array; maintain that x~0~, x~1~ …x~n-1~ are stored consecutively in contents
.
Suggestion: separate size of list and capacity of array. Store
Object[] contents
int size
= # elts in list
| 0 | 1 | 2 | 3 | 4 | 5 | NA | NA | list size 6, capacity 8
How to implement size?
return size;
(make sure size is always correct / updated)
How to imp isEmpty?
return size == 0;
only assumes size is correct.
` return contents[0] == null;` assumes “null” is not a valid entry in List.
How to get(i)?
1
2
check i is valid 0 ≤ i ≤ size()-1
return contents[i];
How to set(i, x)?
1
2
check i is valid 0 ≤ i ≤ size()-1
return contents[i] = x;
How to add(i, x)?
1
2
copy and set
increment size
How to remove(i, x)?
1
2
copy and set
decrement size