Data Structure: initialization, inbound, outbound, and display of stack Elements

Source: Internet
Author: User

[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 () <"";
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.