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.

access this node is to start from the head of the list <strong>and</strong> search all the way through<br />

the list. But such a sequence of l<strong>in</strong>k hopp<strong>in</strong>g operations could take a long time.<br />

3.3 Doubly L<strong>in</strong>ked Lists<br />

As we saw <strong>in</strong> the previous section, remov<strong>in</strong>g an element at the tail of a s<strong>in</strong>gly l<strong>in</strong>ked<br />

list is not easy. Indeed, it is time consum<strong>in</strong>g to remove any node other than the head<br />

<strong>in</strong> a s<strong>in</strong>gly l<strong>in</strong>ked list, s<strong>in</strong>ce we do not have a quick way of access<strong>in</strong>g the node <strong>in</strong> front<br />

of the one we want to remove. Indeed, there are many applications where we do not<br />

have quick access to such a predecessor node. For such applications, it would be nice<br />

to have a way of go<strong>in</strong>g both directions <strong>in</strong> a l<strong>in</strong>ked list.<br />

There is a type of l<strong>in</strong>ked list that allows us to go <strong>in</strong> both directions—forward <strong>and</strong><br />

reverse—<strong>in</strong> a l<strong>in</strong>ked list. It is the doubly l<strong>in</strong>ked list. Such lists allow for a great<br />

variety of quick update operations, <strong>in</strong>clud<strong>in</strong>g <strong>in</strong>sertion <strong>and</strong> removal at both ends, <strong>and</strong><br />

<strong>in</strong> the middle. A node <strong>in</strong> a doubly l<strong>in</strong>ked list stores two references—a next l<strong>in</strong>k,<br />

which po<strong>in</strong>ts to the next node <strong>in</strong> the list, <strong>and</strong> a prev l<strong>in</strong>k, which po<strong>in</strong>ts to the<br />

previous node <strong>in</strong> the list.<br />

A <strong>Java</strong> implementation of a node of a doubly l<strong>in</strong>ked list is shown <strong>in</strong> Code Fragment<br />

3.17, where we assume that elements are character str<strong>in</strong>gs. In Chapter 5, we discuss<br />

how to def<strong>in</strong>e nodes for arbitrary element types.<br />

Code Fragment 3.17: <strong>Java</strong> class DNode represent<strong>in</strong>g<br />

a node of a doubly l<strong>in</strong>ked list that stores a character<br />

str<strong>in</strong>g.<br />

170

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

Saved successfully!

Ooh no, something went wrong!