15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

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

372<br />

Using Deques<br />

Because you can add data to both ends of a deque, a deque can grow in both<br />

directions, as shown in Figure 4-10.<br />

Data #2 Data #1<br />

Data #3<br />

Figure 4-10:<br />

A deque<br />

can grow<br />

in two<br />

different<br />

directions.<br />

Data #4<br />

Data #4<br />

Data #2 Data #1 Data #3<br />

Data #2 Data #1<br />

Data #3<br />

Unlike a stack that always removes the newest data or a queue that always<br />

removes the oldest data, a deque can never predictably remove either the<br />

oldest or newest data. When you add data to both ends of the deque, the<br />

oldest data tends to get sandwiched and buried in between the newest data<br />

on both ends.<br />

Like stacks and queues, deques only allow you to remove data from a specific<br />

part of the data structure. In general, the more complicated the data<br />

structures, the more code you have to write to manage that data structure.<br />

A list or an array is much simpler to use, but much less flexible than a queue<br />

or a stack. Un<strong>for</strong>tunately, stacks, queues, and deques add greater complexity<br />

to your program in exchange <strong>for</strong> their added flexibility.<br />

If you need to store and remove data in an orderly fashion, stacks, queues,<br />

and deques are better suited than arrays, collections, or dictionaries, which<br />

are better suited <strong>for</strong> long-term storage of data. A queue might be useful <strong>for</strong><br />

an online reservation system that handles the oldest request first.<br />

Although the idea of removing the last item first might seem counterintuitive,<br />

stacks are a commonly used data structure. Most programs offer<br />

an Undo command, which lets you undo the last command you gave the<br />

computer. If you give five different commands, the program may store each<br />

command in a stack.<br />

When you want to undo a command, you want to start with the last<br />

command you gave it, which appears on the top of the stack, as shown in<br />

Figure 4-11. Each succeeding Undo command removes an additional command<br />

until you get to the last command, which is the oldest one that was<br />

buried at the bottom of the stack.

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

Saved successfully!

Ooh no, something went wrong!