You are on page 1of 9

Linked Lists

Avoid the drawbacks of fixed size arrays with


Growable arrays Linked lists

Growable arrays
Avoid the problem of fixed-size arrays Increase the size of the array when needed (I.e. when capacity is exceeded) Two strategies:
tight strategy (add a constant): f(N) = N + c growth strategy (double up): f(N) = 2N

Tight Strategy
Add a number k (k = constant) of elements every time the capacity is exceeded
C0 + (C0+k) + (C0+Sk) = S = (N C0) / k Running time? C0 * S + S*(S+1) / 2 O(N2)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Tight Strategy
void insertLast(int rear, element o) { if ( size == rear) { capacity += k; element* B = new element[capacity]; for(int i=0; i<size; i++) { B[i] = A[i]; } A = B; } A[rear] = o; rear++; size++; }

Growth Strategy
Double the size of the array every time is needed (I.e. capacity exceeded)
C0 + (C0 * 2) + (C0*4) + + (C0*2i) = i = log (N / C0) Running time? C0 [1 + 2 + + 2 log(N/C0) ] O(N)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

How does the previous code change?

Linked Lists
Avoid the drawbacks of fixed size arrays with
Growable arrays Linked lists

Using Dynamically Allocated Memory (review)


int i, *pi; float f, *pf; pi = (int *) malloc(sizeof(int)); request memory pf = (float *) malloc (sizeof(float)); *pi =1024; *pf =3.14; printf(an integer = %d, a float = %f\n, *pi, *pf); free(pi); return memory free(pf);

Linked Lists

bat

cat

sat

vat

NULL

Insertion

bat

cat mat

sat

vat

NULL

Compare this with the insertion in arrays!

You might also like