stack.h
#pragma once
#include <iostream>
using namespace std;
#define MAX_SIZE 100
class Stack
{
public:
void init();
void push(int num);
int pop();
bool isFull();
bool isEmpty();
int getTop();
protected:
void test();
private:
int top;
int data[MAX_SIZE];
};
main.cpp
#include <iostream>
#include "stack.h"
using namespace std;
int main()
{
Stack s;
s.init();
for(int i = 0; i < 5; i++)
{
s.push(i);
}
for(int i = 0; i < 5; i++)
{
cout << s.pop() << endl;
}
return 0;
}
stack.cpp
#include "stack.h"
#include <stdio.h>
//#define MAX_SIZE 100
void Stack::init()
{
top = -1;
}
void Stack::push(int num)
{
if(isFull())
{
printf("stack is full!\n");
exit(1);
}
top++;
data[top] = num;
}
int Stack::pop()
{
if(isEmpty())
{
printf("stack is empty!\n");
exit(1);
}
return data[top--];
}
bool Stack::isEmpty()
{
if(top == -1)
{
return true;
}
return false;
}
bool Stack::isFull()
{
if(top == MAX_SIZE -1)
{
return true;
}
return false;
}
int Stack::getTop()
{
return data[top];
}
终端:
judy@judy-virtual-machine:~/桌面/2022/0228$ ./1
4
3
2
1
0
|