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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

In Code Fragment 6.6, we show a <strong>Java</strong> class DNode for the nodes of a doubly<br />

l<strong>in</strong>ked list implement<strong>in</strong>g the position ADT. This class is similar to class DNode<br />

shown <strong>in</strong> Code Fragment 3.17, except that now our nodes store a generic element<br />

<strong>in</strong>stead of a character str<strong>in</strong>g. Note that the prev <strong>and</strong> next <strong>in</strong>stance variables <strong>in</strong> the<br />

DNode class below are private references to other DNode objects.<br />

Code Fragment 6.6: Class DNode realiz<strong>in</strong>g a node<br />

of a doubly l<strong>in</strong>ked list <strong>and</strong> implement<strong>in</strong>g the Position<br />

<strong>in</strong>terface (ADT).<br />

Given a position p <strong>in</strong> S, we can "unwrap" p to reveal the underly<strong>in</strong>g node v. This is<br />

accomplished by cast<strong>in</strong>g the position to a node. Once we have node v, we can, for<br />

example, implement method prev(p) with v.getPrev (unless the node<br />

returned by v.getPrev is the header, <strong>in</strong> which case we signal an error).<br />

Therefore, positions <strong>in</strong> a doubly l<strong>in</strong>ked list implementation can be supported <strong>in</strong> an<br />

object-oriented way without any additional time or space overhead.<br />

Consider how we might implement the addAfter(p, e) method, for <strong>in</strong>sert<strong>in</strong>g<br />

an element e after position p. Similar to the discussion <strong>in</strong> Section 3.3.1, we create a<br />

334

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

Saved successfully!

Ooh no, something went wrong!