Sei sulla pagina 1di 6

Implementation of Lists

Many implementations are possible. Popular ones include:


1. Arrays 2. Pointers (singly linked, doubly linked, etc.) 3. Cursors (arrays with integer pointers)

Array Implementation of Lists


Here, elements of list are stored in the (contiguous) cells of an array. List is a structure with two members. member 1 : an array of elements member 2 : last -- indicates position of the last element of the list

Position is of type integer and has the range 0 to maxlength-1


# define maxlength 1000 typedef int elementtype; /* elements are integers */ typedef struct list-tag { elementtype elements [maxlength]; int last; } list-type; end(L) int end (list-type * { return ( } p p) last + 1)

Insert (x, p,L) void insert (elementtype x ; int p ; list-type * { int v; /* running position */ if ( p last >= maxlength-1) p) ;

error (``list is full'') elseif ((p < 0) || (p > p last + 1))

error (position does not exist) else for (q = p p p } p last ; q <= p, q-) p elements [q] ;

elements [q + 1] = last = p

last + 1 ;

elements [p] = x

Delete (p, L) void delete (int p ; list-type * { int q ; /* running position */ if ((p > p last) || (p < 0)) p)

error (``position does not exist'')

else /* shift elements */ { p last - ; p last; q ++) p elements [q+1]

for (q = p ; q <= p } }

elements [q] =

Locate (x, L) int locate (element type *x ; list-type * { int q ; for (q = 0 ; q <= if ( p p last ; q++) p)

elements [q] = = x]

return (q) ; return ( } p last + 1) /* if not found */

Pointer Implementation of Lists

In the array implementation, 1. we are constrained to use contiguous space in the memory 2. Insertion, deletion entail shifting the elements

Pointers overcome the above limitations at the cost of extra space for pointers.

Singly Linked List Implementation A list a1, a2,..., an is organized as shown in Figure 2.1

Figure 2.1: A singly linked list

Let us follow a convention that position i is a pointer to the cell holding the pointer to the cell containing ai, (for i = 1, 2,..., n). Thus, o Position 1 is a pointer to the header o End (L) is a pointer to the last cell of list L If position of ai is simply a pointer to the cell holding ai, then o Position 1 will be the address in the header o end (L) will be a null pointer Insert (x, p, L) : See Figure 2.2 Delete (x, L) : See Figure 2.3

Figure 2.2: Insertion in a singly linked list

Figure 2.3: Deletion in a singly linked list

Doubly Linked List Implementation


* *

makes searches twice as efficient needs as many extra pointers as the number of elements (See Figure 2.4); consequently insertions and deletions are more expensive in terms of pointer assignments

Figure 2.4: A doubly linked list

Potrebbero piacerti anche