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.

S<strong>in</strong>ce the deque requires <strong>in</strong>sertion <strong>and</strong> removal at both ends of a list, us<strong>in</strong>g a s<strong>in</strong>gly<br />

l<strong>in</strong>ked list to implement a deque would be <strong>in</strong>efficient. We can use a doubly l<strong>in</strong>ked<br />

list, however, to implement a deque efficiently. As discussed <strong>in</strong> Section 3.3,<br />

<strong>in</strong>sert<strong>in</strong>g or remov<strong>in</strong>g elements at either end of a doubly l<strong>in</strong>ked list is<br />

straightforward to do <strong>in</strong> O(1) time, if we use sent<strong>in</strong>el nodes for the header <strong>and</strong><br />

trailer.<br />

For an <strong>in</strong>sertion of a new element e, we can have access to the node p before the<br />

place e should go <strong>and</strong> the node q after the place e should go. To <strong>in</strong>sert a new<br />

element between the two nodes p <strong>and</strong> q (either or both of which could be sent<strong>in</strong>els),<br />

we create a new node t, have t's prev <strong>and</strong> next l<strong>in</strong>ks respectively refer to p <strong>and</strong> q,<br />

<strong>and</strong> then have p's next l<strong>in</strong>k refer to t, <strong>and</strong> have q's prev l<strong>in</strong>k refer to t.<br />

Likewise, to remove an element stored at a node t, we can access the nodes p <strong>and</strong> q<br />

on either side of t (<strong>and</strong> these nodes must exist, s<strong>in</strong>ce we are us<strong>in</strong>g sent<strong>in</strong>els). To<br />

remove node t between nodes p <strong>and</strong> q, we simply have p <strong>and</strong> q po<strong>in</strong>t to each other<br />

<strong>in</strong>stead of t. We need not change any of the fields <strong>in</strong> t, for now t can be reclaimed<br />

by the garbage collector, s<strong>in</strong>ce no one is po<strong>in</strong>t<strong>in</strong>g to t.<br />

Table 5.3 shows the runn<strong>in</strong>g times of methods for a deque implemented with a<br />

doubly l<strong>in</strong>ked list. Note that every method runs <strong>in</strong> O(1) time.<br />

Table 5.3: Performance of a deque realized by a<br />

doubly l<strong>in</strong>ked list.<br />

Method<br />

Time<br />

size, isEmpty<br />

O(1)<br />

getFirst, getLast<br />

O(1)<br />

add First, addLast<br />

O(1)<br />

removeFirst, removeLast<br />

O(1)<br />

300

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

Saved successfully!

Ooh no, something went wrong!