如何手动实现一个栈

版权声明:小简原创 https://blog.csdn.net/qq_43469554/article/details/87731114
#include <iostream>
using namespace std;
struct Stack{
    int data[10000];
    int top = -1;
    void push(int x)
    {
        top++;
        if (top < 10000)
        {
            data[top] = x;
        }
        else
        {
            top--;
            cout << "stack overflow" << endl;
        }  
    }
    void pop()
    {
        if (top >= 0)
        {
            top--;
		}
    }
    int topval()
    {
        if (top >= 0)
        {
            return data[top];
        }
    }
};

int main() {
    Stack s;
    for (int i = 1; i <= 10; i++)
    {
        s.push(i);
	}
    for (int i = 1; i <= 10; i++)
    {
        cout << s.topval() << " ";
        s.pop();
    }
    return 0;
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43469554/article/details/87731114