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.

5.1.2 A Simple Array-Based Stack Implementation<br />

We can implement a stack by stor<strong>in</strong>g its elements <strong>in</strong> an array. Specifically, the stack<br />

<strong>in</strong> this implementation consists of an N-element array S plus an <strong>in</strong>teger variable t<br />

that gives the the <strong>in</strong>dex of the top element <strong>in</strong> array S. (See Figure 5.2.)<br />

Figure 5.2: Implement<strong>in</strong>g a stack with an array S.<br />

The top element <strong>in</strong> the stack is stored <strong>in</strong> the cell S[t].<br />

Recall<strong>in</strong>g that arrays start at <strong>in</strong>dex 0 <strong>in</strong> <strong>Java</strong>, we <strong>in</strong>itialize t to −1, <strong>and</strong> we use this<br />

value for t to identify an empty stack. Likewise, we can use t to determ<strong>in</strong>e the<br />

number of elements (t + 1). We also <strong>in</strong>troduce a new exception, called<br />

FullStackException, to signal the error that arises if we try to <strong>in</strong>sert a new<br />

element <strong>in</strong>to a full array. Exception FullStackException is specific to this<br />

implementation <strong>and</strong> is not def<strong>in</strong>ed <strong>in</strong> the stack ADT, however. We give the details<br />

of the array-based stack implementation <strong>in</strong> Code Fragment 5.3.<br />

Code Fragment 5.3:<br />

array of a given size, N.<br />

Implement<strong>in</strong>g a stack us<strong>in</strong>g an<br />

267

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

Saved successfully!

Ooh no, something went wrong!