Professional Documents
Culture Documents
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) =
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
S = (N C0) / k
Running time? C0 * S + S*(S+1) / 2 O(N2)
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)
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
Linked Lists
Avoid the drawbacks of fixed size arrays with
Growable arrays Linked lists
Linked Lists
bat
cat
sat
vat
NULL
Insertion
bat
cat mat
sat
vat
NULL
Deletion
bat
cat
sat
vat NULL
List ADT
ADT with position-based methods generic methods size(), isEmpty() query methods isFirst(p), isLast(p) accessor methods first(), last() before(p), after(p) update methods swapElements(p,q), replaceElement(p,e) insertFirst(e), insertLast(e) insertBefore(p,e), insertAfter(p,e) removeAfter(p)
Implementation
Declaration
typedef struct node, *pnode; typedef struct node { char data [4]; pnode next; }; Creation pnode ptr =NULL; Testing #define IS_EMPTY(ptr) (!(ptr)) Allocation ptr=(pnode) malloc (sizeof(node));
ptr b a
data t \0
ptr
20
NULL
strcpy(temp->data, data); if (node) { noempty list temp->next=node->next; node->next= temp; } else { empty list temp->next= NULL; node =temp; } }
node
10 20 NULL
50
temp
Deletion
node 10 trail = NULL 50 20 NULL node 50 20 NULL
(a) before deletion Delete node other than the first node
head
10
(b)after deletion
node
50 20 NULL
head
10 20 NULL
void removeAfter(pnode node) { /* delete what follows after node in the list */ node pnode tmp; if (node) { 50 10 tmp = node -> next; node->next = node->next->next; 20 NULL free(tmp); 10 } }
20 NULL
Traverse a list
void traverseList(pnode ptr) { printf(The list contains: ); for ( ; ptr; ptr = ptr->next) printf(%4d, ptr->data); printf(\n); }