23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

PositionList <strong>in</strong>terfaces (def<strong>in</strong>ed for any generic<br />

type E), <strong>and</strong> adds two more methods.<br />

Implement<strong>in</strong>g a Sequence with an Array<br />

If we implement the sequence S ADT with a doubly l<strong>in</strong>ked list, we would get<br />

similar performance to that of the java.util.L<strong>in</strong>kedList class. So suppose<br />

<strong>in</strong>stead we want to implement a sequence S by stor<strong>in</strong>g each element e of S <strong>in</strong> a<br />

cell A[i] of an array A. We can def<strong>in</strong>e a position object p to hold an <strong>in</strong>dex i <strong>and</strong> a<br />

reference to array A, as <strong>in</strong>stance variables, <strong>in</strong> this case. We can then implement<br />

method element(p) simply by return<strong>in</strong>g A[i]. A major drawback with this<br />

approach, however, is that the cells <strong>in</strong> A have no way to reference their<br />

correspond<strong>in</strong>g positions. Thus, after perform<strong>in</strong>g an add First operation, we<br />

have no way of <strong>in</strong>form<strong>in</strong>g the exist<strong>in</strong>g positions <strong>in</strong> S that their <strong>in</strong>dices each went<br />

up by 1 (remember that positions <strong>in</strong> a sequence are always def<strong>in</strong>ed relative to their<br />

neighbor<strong>in</strong>g positions, not their <strong>in</strong>dices). Hence, if we are go<strong>in</strong>g to implement a<br />

general sequence with an array, we need a different approach.<br />

Consider an alternate solution, then, <strong>in</strong> which, <strong>in</strong>stead of stor<strong>in</strong>g the elements of S<br />

<strong>in</strong> array A, we store a new k<strong>in</strong>d of position object <strong>in</strong> each cell of A, <strong>and</strong> we store<br />

elements <strong>in</strong> positions. The new position object p holds the <strong>in</strong>dex i <strong>and</strong> the element<br />

e associated with p.<br />

With this data structure, illustrated <strong>in</strong> Figure 6.8, we can easily scan through the<br />

array to update the <strong>in</strong>dex variable i for each position whose <strong>in</strong>dex changes<br />

because of an <strong>in</strong>sertion or deletion.<br />

Figure 6.8: An array-based implementation of the<br />

sequence ADT.<br />

354

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!