Section9.75a

]>
Book Contents Previous Section 9.75 SquareFreeRegularTriangularSet Next Section 9.76 Stream Book Index

## 9.75a Stack

A stack is an aggregate structure which allows insertion, deletion, and inspection of the "top" element. Stacks are similar to any pile of paper where you can only add to the pile, remove the top paper from the file, or read the top paper.

Stacks can be created from a list of elements using the stack Stack function.

a:Stack INT:= stack [1,2,3,4,5]

[ 1 , 2 , 3 , 4 , 5 ]

Type: Stack Integer

An empty stack can be created using the empty function.

a:Stack INT:= empty()

[ ]

Type: Stack Integer

The empty? function will return true if the stack contains no elements.

empty? a

true

Type: Boolean

Stacks modify their arguments so they use the exclamation mark "!" as part of the function name.

The pop! function removes the top element of the stack and returns it. The stack is one element smaller. The extract! function does the same thing with a different name.

a:Stack INT:= stack [1,2,3,4,5]

[ 1 , 2 , 3 , 4 , 5 ]

Type: Stack Integer
pop! a

1

Type: PositiveInteger
a

[ 2 , 3 , 4 , 5 ]

Type: Stack Integer

The push! function adds a new top element to the stack and returns the element that was pushed. The stack is one element larger. The insert! function does the same thing with a different name.

a:Stack INT:= stack [1,2,3,4,5]

[ 1 , 2 , 3 , 4 , 5 ]

Type: Stack Integer
push!(9,a)

9

Type: PositiveInteger
a

[ 1 , 2 , 3 , 4 , 5 , 9 ]

Type: Stack Integer

To read the top element without changing the stack use the top function.

a:Stack INT:= stack [1,2,3,4,5]

[ 1 , 2 , 3 , 4 , 5 ]

Type: Stack Integer
top a

1

Type: PositiveInteger
a

[ 1 , 2 , 3 , 4 , 5 ]

Type: Stack Integer
Book Contents Previous Section 9.75 SquareFreeRegularTriangularSet Next Section 9.76 Stream Book Index