Implement basic stack operations with arrays

Basic description of the topic: Given an array with a given size, represented by n, let you design a program and use the array to implement the basic operations of the stack

Ideas:

The stack is first-in-last-out. First, a variable index is defined, which means that if a number is placed (push operation), it should be placed at the index position of the array (it also represents how many numbers are in the current stack).

Push operation: If the index is equal to the size of the array, it means that the number in the stack is full, and an error is reported to the user. Otherwise, put the number into the index position of the array, and then increase the index by 1.

pop operation: If the index is equal to 0, it means that there are no numbers in the stack, and an error is reported to the user. Otherwise, the number at the position where the index is decreased by 1 is output, and then the index is decreased by 1.

code show as below:

#include<bits/stdc++.h>
using namespace std;
int a[3];
int index=0; //Indicates adding a number, where should it be added, and also represents how many numbers are in the current stack
string b;
void push(int n)
{
    if(index==3) //When the number in the current queue is full, but the number still needs to be added, an error should be reported at this time
        cout<<"error"<<endl;
    else
            a[index++ ]=n;
}
void pop()
{
    if(index==0) //When there are no numbers in the queue, you still want to take out numbers from the queue, you should also report an error
        cout<<"error"<<endl ;
    else
        cout<<a[--index]<<endl; //There is no need to judge whether it is out of bounds, because it is --, only when index is equal to 0, --index will go out of bounds, but this situation has been judged above so it can't happen
}
int main()
{
    while (cin>>b)
    {
        if(b=="push")
        {
            int number;
            cin>>number;
            push(number);
        }
        if(b=="pop")
            pop();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325767828&siteId=291194637