- _stack.h
#ifndef _STACK_H
#define _STACK_H
#define STACK_SIZE 50
#include <iostream>
#include <stdlib.h>
using namespace std;
#define STACK_SIZE 50
typedef int Elemment;
typedef struct _stack
{
int elem[STACK_SIZE];
Elemment top;
}SeqStack;
#endif
- stack.h
#ifndef STACK_H
#define SRACK_H
#include "_stack.h"
void InitStack(SeqStack *s);
bool Push(SeqStack *s, Elemment x);
bool Pop(SeqStack *s, Elemment *x);
bool GetStack(SeqStack *s, Elemment *x);
#endif
- stack.cpp
#include "_stack.h"
void InitStack(SeqStack *s)
{
s->top = -1;
}
bool Push(SeqStack *s, Elemment x)
{
if (s->top == STACK_SIZE-1)
{
return false;
}
else
{
s->top++;
s->elem[s->top] = x;
return true;
}
}
bool Pop(SeqStack *s, Elemment *x)
{
if (s->top == -1)
{
return false;
}
else
{
*x = s->elem[s->top];
s->top--;
return true;
}
}
bool GetStack(SeqStack *s, Elemment *x)
{
if (s->top == -1)
{
return false;
}
else
{
*x = s->elem[s->top];
return true;
}
}
- main.cpp
#include "_stack.h"
#include "stack.h"
int main(void)
{
SeqStack s ;
InitStack(&s);
for (int i = 1; i < 10; i++)
{
bool flag;
flag = Push(&s, 2 * i);
if (!flag)
{
break;
}
}
int temp = 0;
bool flag = GetStack(&s, &temp);
if (flag)
{
cout << temp << endl;
}
flag = Pop(&s, &temp);
while (flag)
{
cout << temp << " ";
flag = Pop(&s, &temp);
}
cout << endl;
int x =0 ;
flag = Push(&s, x);
if (flag)
{
cout << temp<<endl;
}
else
{
cout << "栈为空!" << endl;
}
return 0;
}