1.初始化一个栈;
2.测试初始化后的栈是否为空;
3.测试一个栈是否已满;
4.在栈的顶端插入一个元素。简称,入栈;该操作相当于在栈的最后一个位置栈顶位置插入一个新的元素。
5.删除栈的栈顶元素;
6.取当前栈顶元素;
code:
// stack.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "stack.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
extern int top;
Initials(top);
Insert(top,4);
Insert(top,1);
cout << GetStackTop(top) << endl;
DeleteTopElem(top);
cout << GetStackTop(top) << endl;
return 0;
}
// stack.h
#ifndef STACK_H_
#define STACK_H_
//
// 初始化一个栈;
#define MaxSize 1000
int stack[MaxSize];
int top;
// 初始化栈的操作是为了令栈的栈顶指针指向-1;
void Initials(int& top)
{
top == -1;
}
//
// 测试一个栈是否为空;
bool IsEmpty(int& top)
{
return top == -1;
}
//
// 测试栈是否已经满了
bool IsFull(int& top)
{
return top == MaxSize - 1;
}
//
// 删除栈顶元素;
void DeleteTopElem(int& top)
{
if (IsEmpty(top))
{
throw"栈是空的";
}
else
{
top --;
}
}
//
// 在栈的栈顶插入一个元素;
void Insert(int& top,int elem)
{
if (IsFull(top))
{
throw"栈满了!";
}
else
{
stack[++ top] = elem;
}
}
//
// 获得当前栈顶元素;
int GetStackTop(int& top)
{
if (!IsEmpty(top))
{
return stack[top];
}
}
#endif