The Stack component represents a common structure in computing often used to reverse the order of data. An analogy of its behavior is that of a stack of plates in a cafeteria. When you add plates to the stack they go on top of the stack and when you take plates from the stack you take them from the top. The result is that plates added last are always the ones that are withdrawn first.

A stack is stored in memory in a way similar to an array (see http://www.codemorphis.com/forums/viewtopic.php?t=34 for a treatment on the array component) but the stack has two important services used to add and remove data. These services are the “Push” and “Pop” services. The “Push” service is used to add data to the top of the stack (akin to pushing down the stack of plates when we add a new plate). The “Pop” service is used to remove and retrieve the topmost data on the stack (akin to removing the topmost plate on the stack of cafeteria plates).

In the simple program below we use the “Push” service to add ten string elements to a stack. The program uses the “Print” service of the Stack component to output the contents of the stack to the console.

In the example below, we have modified the program by adding a For Loop component which counts from 0 to 9 inclusive (Input Data Port 0 has a start value of 0, Input Data Port 1 has an end value of 9, Input Data Port 2 has an increment value of 1). For each loop iteration the “Pop” service of the Stack component is called. Each call to the “Pop” service retrieves the data from the top of the stack and passes it to the Console Print component which outputs the data to the console. Since the loop goes from 0 to 9 inclusive, we call the “Pop” service a total of ten times, which empties the stack one data element at a time. This program effectively retrieves the data in reverse order, as you can see in the console.

Our program works fine but it assumes that the number of data elements stored in the stack is 10. We could make use of the Stack component’s “Num items” service to determine the current number of data elements and then feed that number into Input Data Port 1 of the For Loop component but this is a rather cumbersome and inefficient way to go about things. It is better to use the “Get empty” service of the Stack component which simply tells us if there are more elements in the stack. This service returns “TRUE” if the stack is empty and “FALSE” otherwise.

Another useful service is the “Reverse” service which of course reverses the order of the data elements in the stack. In the example below, we can see that after calling the “Reverse” service, the console print of the stack shows that the elements are now stored in reverse order. Compare this output to the output in the first snapshot above.