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.

we <strong>in</strong>dicate that the stack no longer needs to hold a reference to object e. Indeed,<br />

if there are no other active references to e, then the memory space taken by e will<br />

be reclaimed by the garbage collector.<br />

Table 5.1 shows the runn<strong>in</strong>g times for methods <strong>in</strong> a realization of a stack by an<br />

array. Each of the stack methods <strong>in</strong> the array realization executes a constant<br />

number of statements <strong>in</strong>volv<strong>in</strong>g arithmetic operations, comparisons, <strong>and</strong><br />

assignments. In addition, pop also calls isEmpty, which itself runs <strong>in</strong> constant<br />

time. Thus, <strong>in</strong> this implementation of the Stack ADT, each method runs <strong>in</strong><br />

constant time, that is, they each run <strong>in</strong> O(1) time.<br />

Table 5.1: Performance of a stack realized by an<br />

array. The space usage is O(N), where N is the size of<br />

the array, determ<strong>in</strong>ed at the time the stack is<br />

<strong>in</strong>stantiated. Note that the space usage is <strong>in</strong>dependent<br />

from the number n ≤ N of elements that are actually<br />

<strong>in</strong> the stack.<br />

Method<br />

Time<br />

size<br />

O(1)<br />

is Empty<br />

O(1)<br />

top<br />

O(1)<br />

push<br />

O(1)<br />

pop<br />

O(1)<br />

A concrete <strong>Java</strong> implementation of the pseudo-code of Code Fragment 5.3, with<br />

<strong>Java</strong> class ArrayStack implement<strong>in</strong>g the Stack <strong>in</strong>terface, is given <strong>in</strong> Code<br />

Fragments 5.4 <strong>and</strong> 5.5. Unfortunately, due to space considerations, we omit most<br />

269

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

Saved successfully!

Ooh no, something went wrong!