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.

get(size() −1)<br />

addFirst(e)<br />

add(0,e)<br />

addLast(e)<br />

add(size(),e)<br />

removeFirst()<br />

remove(0)<br />

removeLast()<br />

remove(size() − 1)<br />

6.1.3 A Simple Array-Based Implementation<br />

An obvious choice for implement<strong>in</strong>g the array list ADT is to use an array A, where<br />

A[i] stores (a reference to) the element with <strong>in</strong>dex i. We choose the size N of array<br />

A sufficiently large, <strong>and</strong> we ma<strong>in</strong>ta<strong>in</strong> the number of elements <strong>in</strong> an <strong>in</strong>stance<br />

variable, n < N.<br />

The details of this implementation of the array list ADT are simple. To implement<br />

the get(i) operation, for example, we just return A[i]. Implementations of<br />

methods add(i, e) <strong>and</strong> remove(i) are given <strong>in</strong> Code Fragment 6.1. An<br />

important (<strong>and</strong> time-consum<strong>in</strong>g) part of this implementation <strong>in</strong>volves the shift<strong>in</strong>g of<br />

elements up or down to keep the occupied cells <strong>in</strong> the array contiguous. These<br />

shift<strong>in</strong>g operations are required to ma<strong>in</strong>ta<strong>in</strong> our rule of always stor<strong>in</strong>g an element<br />

whose list <strong>in</strong>dex is i at <strong>in</strong>dex i <strong>in</strong> the array A. (See Figure 6.1 <strong>and</strong> also Exercise R-<br />

6.12.)<br />

Code Fragment 6.1: Methods add(i, e) <strong>and</strong><br />

remove(i) <strong>in</strong> the array implementation of the array<br />

list ADT. We denote, with n, the <strong>in</strong>stance variable<br />

stor<strong>in</strong>g the number of elements <strong>in</strong> the array list.<br />

317

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

Saved successfully!

Ooh no, something went wrong!