
Data Structure

This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.
A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO.

The stack is accessed through its top.

The basic stack operations are:

   push   stores a new element onto the stack top;
   pop   returns the last pushed stack element, while removing it from the stack;
   empty   tests if the stack contains no elements.


Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):

   top   (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.


Stacks allow a very simple hardware implementation.

They are common in almost all processors.

In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.

Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).

This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.

See stack machine.

Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.



Task

Create a stack supporting the basic operations: push, pop, empty.



See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


100  DIM STACK$(1000)
110  DATA "(2*A)","PI","","TO BE OR","NOT TO BE"
120  FOR I = 1 TO 5
130  READ ELEMENT$
140  GOSUB 500_PUSH
150  NEXT 
200  GOSUB 400 POP  AND  PRINT 
210  GOSUB 300_EMPTY AND  PRINT 
220  FOR I = 1 TO 4
230  GOSUB 400 POP  AND  PRINT 
240  NEXT 
250  GOSUB 300_EMPTY AND  PRINT 
260  END 
300  GOSUB 700_EMPTY
310  PRINT "STACK IS ";
320  IF  NOT EMPTY THEN  PRINT "NOT ";
330  PRINT "EMPTY"
340  RETURN 
400  GOSUB 600 POP 
410  PRINT ELEMENT$
420  RETURN 
500  REM 
510  REM PUSH
520  REM 
530  LET STACK$(SP) = ELEMENT$
540  LET SP = SP + 1
550  RETURN 
600  REM 
610  REM POP
620  REM 
630  IF SP THEN SP = SP - 1
640  LET ELEMENT$ = STACK$(SP)
650  LET STACK$(SP) = ""
660  RETURN 
700  REM 
710  REM EMPTY
720  REM 
730  LET EMPTY = SP = 0
740  RETURN
 