Documente Academic
Documente Profesional
Documente Cultură
02
Data Structures
Implementing Lists
We have designed the interface for the List; we
now must consider how to implement that
interface.
Implementing Lists
We have designed the interface for the List; we
now must consider how to implement that
interface.
Implementing Lists using an array: for example,
the list of integers (2, 6, 8, 7, 1) could be
represented as:
current size
A 2 6 8 7 1
3 5
1 2 3 4 5
List Implementation
add(9); current position is 3. The new list would thus
be: (2, 6, 8, 9, 7, 1)
We will need to shift everything to the right of 8 one
place to the right to make place for the new element ‘9’.
current size
step 1: A 2 6 8 7 1
3 5
1 2 3 4 5 6
current size
Step 2: A 2 6 8 9 1
5 5
1 2 3 4 5
Implementing Lists
remove(): removes the element at the current
index
current size
Step 1: A 2 6 8 9 1
5 6
1 2 3 4 5 6
5
current size
Step 2: A 2 6 8 9 1
5 5
1 2 3 4 5
int find(int X)
{
int j;
for(j=1; j < size+1; j++ )
if( A[j] == X ) break;
find
Worst-case: may have to search the entire array
Average-case: search at most half the array.
object next
head
2 6 8 7 1 size=5
current
Linked List
Note some features of the list:
Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
Linked List
Note some features of the list:
Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
The current here is a pointer, not an index.
Linked List
Note some features of the list:
Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
The current here is a pointer, not an index.
The next field in the last node points to nothing.
We will place the memory address NULL which
is guaranteed to be inaccessible.
Linked List
Actual picture in memory:
1051 6
1052 1063
current 1053 1063
1054 2
head 1055 1051
1056
2 6 8 7 1 1057 7
1058 1060
current 1059
1060 1
1061 0
head 1062 1054
1063 8
1064 1057
1065