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.

Like an array, a s<strong>in</strong>gly l<strong>in</strong>ked list keeps its elements <strong>in</strong> a certa<strong>in</strong> order. This order is<br />

determ<strong>in</strong>ed by the cha<strong>in</strong> of next l<strong>in</strong>ks go<strong>in</strong>g from each node to its successor <strong>in</strong> the<br />

list. Unlike an array, a s<strong>in</strong>gly l<strong>in</strong>ked list does not have a predeterm<strong>in</strong>ed fixed size, <strong>and</strong><br />

uses space proportional to the number of its elements. Likewise, we do not keep track<br />

of any <strong>in</strong>dex numbers for the nodes <strong>in</strong> a l<strong>in</strong>ked list. So we cannot tell just by<br />

exam<strong>in</strong><strong>in</strong>g a node if it is the second, fifth, or twentieth node <strong>in</strong> the list.<br />

Implement<strong>in</strong>g a S<strong>in</strong>gly L<strong>in</strong>ked List<br />

To implement a s<strong>in</strong>gly l<strong>in</strong>ked list, we def<strong>in</strong>e a Node class, as shown <strong>in</strong> Code<br />

Fragment 3.12, which specifies the type of objects stored at the nodes of the list.<br />

Here we assume elements are character str<strong>in</strong>gs. In Chapter 5, we describe how to<br />

def<strong>in</strong>e nodes that can store arbitrary types of elements. Given the Node class, we<br />

can def<strong>in</strong>e a class, SL<strong>in</strong>kedList, shown <strong>in</strong> Code Fragment 3.13, def<strong>in</strong><strong>in</strong>g the<br />

actual l<strong>in</strong>ked list. This class keeps a reference to the head node <strong>and</strong> a variable<br />

count<strong>in</strong>g the total number of nodes.<br />

Code Fragment 3.12:<br />

s<strong>in</strong>gly l<strong>in</strong>ked list.<br />

Implementation of a node of a<br />

Code Fragment 3.13: Partial implementation of the<br />

class for a s<strong>in</strong>gly l<strong>in</strong>ked list.<br />

165

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

Saved successfully!

Ooh no, something went wrong!