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.

362<br />

Using a Stack<br />

Data #3<br />

Figure 4-1:<br />

Stacks store<br />

the oldest<br />

data on the<br />

bottom and<br />

the newest<br />

data on top.<br />

Data #2 Data #3<br />

Data #1 Data #2<br />

Data #1<br />

Adding new data to a stack pushes the<br />

oldest data further down the stack.<br />

Data #3<br />

Data #2<br />

Data #1<br />

Data #2<br />

Data #1<br />

Removing data from a<br />

stack takes away the<br />

newest data.<br />

The only way to remove data from a stack is from its top. Each time you<br />

remove data, the stack shrinks automatically. Because a stack only lets you<br />

remove the last item stored on the stack, it’s often called a Last In, First Out<br />

(LIFO) data structure because the last item stored is always the first item<br />

you can remove from the stack.<br />

Few <strong>programming</strong> languages offer the stack data structure as a built-in feature.<br />

Instead, you have to create a stack using other data structures, such as<br />

an array or a linked list. When you create another data structure out of a<br />

built-in data structure, the new data structure created is an abstract data<br />

structure. To save you the time and trouble of creating a stack data structure,<br />

many <strong>programming</strong> language compilers come with libraries (or classes in<br />

object-oriented languages) of subprograms that have created the stack data<br />

structure <strong>for</strong> you.<br />

Because a stack is just a data structure, you can declare a variable to represent<br />

a stack in Visual Basic.NET by doing the following:<br />

Dim BlowMyStack as New Stack<br />

This command simply identifies a BlowMyStack variable as a stack data<br />

structure. The New command tells the computer to create a new stack.<br />

Adding data to a stack<br />

When you first create a stack, it contains zero items. Each time you add a<br />

new chunk of data to a stack, it expands automatically. Unlike other data<br />

structures, such as collections, you can only add new data to the top of the<br />

stack; you can never add data in a specific location in a stack.

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

Saved successfully!

Ooh no, something went wrong!