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 a Stack 363<br />

Like a collection or a dictionary, a stack can typically hold different data,<br />

such as both numbers and strings.<br />

The only way you can store or remove data from a stack is through the top<br />

of the stack. To add data to a stack, you push that data on the stack. In Visual<br />

Basic.NET, you specify the Push command along with the stack name like<br />

this:<br />

Dim BlowMyStack as New Stack<br />

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

This command stores the string “My cat” on top of the stack. Each time you<br />

add another chunk of data to a stack, you have to put that data on the top,<br />

which pushes any existing data farther down the stack.<br />

If you added the string “My cat,” the number 108.75, and the string “Fat dog,”<br />

the stack would look like Figure 4-2.<br />

Dim BlowMyStack as New Stack<br />

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

BlowMyStack.Push (108.75)<br />

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

Figure 4-2:<br />

When you<br />

add data<br />

to a stack,<br />

the oldest<br />

data keeps<br />

getting<br />

pushed<br />

farther down<br />

the stack.<br />

108.75 Fat dog<br />

My cat 108.75<br />

My cat<br />

Fat dog<br />

108.75<br />

My cat<br />

Book III<br />

Chapter 4<br />

Stacks, Queues,<br />

and Deques<br />

Removing data from a stack<br />

After you store data in a stack, the only way you can remove data from that<br />

stack is by removing the top item. Removing data from a stack is known as<br />

popping the data off the stack. If you just want to retrieve the data from a<br />

stack without removing it, you can use a Peek command, which lets you<br />

retrieve the top item from a stack.

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

Saved successfully!

Ooh no, something went wrong!