Using Icon lists as stacks
Lists don't have to stay the same size. You can add or subtract elements at either end of a list. This allows you to use a list as a pushdown stack.
push(L, x)'' adds x as the new first element of list L.
pop(L)'' removes the first element of list L and returns its value; this function fails if the list is empty.
Here is an example. This program writes the lines of its input in reverse order, by pushing each line as it is read, and then writing each line as it is popped:
procedure main() stack := ; # Make `stack' an empty list while push ( stack, read ( ) ); # Read and push each line while write ( pop ( stack ) ); # Pop and write each line endThe first ``
while'' statement calls the ``
read()'' function repeatedly. Each time a line is read, it is pushed onto the stack. The second loop calls the ``
pop()'' function repeatedly, and each time it succeeds, the value is written to the output.
John Shipman, email@example.com
Last updated: 1996/01/06 21:12:57 UT