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.

Using Queues 365<br />

Counting and searching a stack<br />

Because stacks can expand and shrink depending on the amount of data you<br />

push on them, many <strong>programming</strong> languages give you commands to count<br />

the total number of items currently stored in a stack.<br />

In Visual Basic.NET, the command to count the number of items currently<br />

stored in a stack is Count. Here’s an example:<br />

Dim BlowMyStack as New Stack<br />

Dim X as Object<br />

BlowMyStack.Push (“My cat”)<br />

BlowMyStack.Push (108.75)<br />

BlowMyStack.Push (“Fat dog”)<br />

X = BlowMyStack.Count<br />

In this example, the Count command stores the number 3 in the X variable.<br />

Visual Basic.NET also provides a Contains command, which tells you<br />

whether a chunk of data is stored in a stack (but doesn’t tell you the location<br />

of that data in the stack). To use the Contains command, you have to specify<br />

the data you want to find like this:<br />

Dim BlowMyStack as New Stack<br />

Dim X, Y as Object<br />

BlowMyStack.Push (“My cat”)<br />

BlowMyStack.Push (108.75)<br />

BlowMyStack.Push (“Fat dog”)<br />

X = BlowMyStack.Contains(“Good dog”)<br />

Y = BlowMyStack.Contains(“Fat dog”)<br />

In this example, the first Contains command looks <strong>for</strong> the “Good dog”<br />

string. Because this string isn’t stored in the stack, the Contains command<br />

returns a False value, which it stored in the X variable.<br />

Book III<br />

Chapter 4<br />

Stacks, Queues,<br />

and Deques<br />

The second Contains command looks <strong>for</strong> the “Fat dog” string. Because this<br />

string is stored in the stack, this Contains command returns a True value,<br />

which is stored in the Y variable.<br />

The Contains command tells you whether a chunk of data is in a stack, but<br />

it doesn’t tell you where in the stack that data might be.<br />

Using Queues<br />

Similar to a stack is another data structure — a queue.

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

Saved successfully!

Ooh no, something went wrong!