[Cpp]
# Include <iostream. h>
Const int MAX = 5; // assume that the stack can store up to 5 data records
// Define a class named stack, which has the stack Function
Class stack {
// Data member
Float num [MAX]; // array for storing stack data
Int top; // variable indicating the top position of the stack
Public:
// Member functions
Void init (void) {top = 0;} // initialize the Function
Void push (float x) // function of the inbound Stack
{
If (top = MAX ){
Cout <"Stack is full! "<Endl;
Return;
};
Num [top] = x;
Top ++;
}
Float pop (void) // function of the output Stack
{
Top --;
If (top <0 ){
Cout <"Stack is underflow! "<Endl;
Return 0;
};
Return num [top];
}
}
// The following is the main () function, which uses the stack class to create stack objects and uses these objects
Main (void)
{
// Declare variables and objects
Int I;
Float x;
Stack a, B; // declare (create) stack object
// Initialize the stack object
A. init ();
B. init ();
// The following uses the loop and push () member functions to import the objects of stack a in sequence from 2, 4, 6, 8, and 10.
For (I = 1; I <= MAX; I ++)
A. push (2 * I );
// The following uses the loop and pop () member functions to pop up data in stack a and display
For (I = 1; I <= MAX; I ++) www.2cto.com
Cout <a. pop () <"";
Cout <endl;
// The following uses the loop and push () member functions to import the data input by the keyboard to stack B in sequence.
Cout <"Please input five numbers." <endl;
For (I = 1; I <= MAX; I ++ ){
Cin> x;
B. push (x );
}
// The following uses the loop and pop () member functions to pop up data in stack B and display
For (I = 1; I <= MAX; I ++)
Cout <B. pop () <"";
}