stack.h
/*-----------------------------------------------
Created By EverSteins Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#ifndef QUEUE_H
#define QUEUE_H
#include "utility.h"
typedef int ElemType;
class Stack
{
public:
Stack():top_(0){}
bool Empty() const //内联
{
return top_ == 0;
}
bool Full() const //内联
{
return top_ == kMaxStack;
}
size_t Size() const //内联
{
return top_ + 1;
}
bool Pop();
bool Top(ElemType &item) const;
bool Push(const ElemType &item);
private:
static const size_t kMaxStack = 3;
size_t top_;
ElemType entry_[kMaxStack];
};
#endif
stack.cpp
/*-----------------------------------------------
Created By EverSteins Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#include "stdafx.h"
#include "utility.h"
#include "stack.h"
bool Stack::Pop()
{
if (Empty())
return false;
top_--; //记得top_--
return true;
}
bool Stack::Top(ElemType &item) const
{
if (Empty())
return false;
item=entry_[top_];
return true;
}
bool Stack::Push(const ElemType &item)
{
if (Full()) //不要忘了判断是否溢出
return false;
entry_[top_++]=item; //记得top_++
return true;
}
utility.h
/*-----------------------------------------------
Created By EverSteins Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#ifndef UTILITY_H
#define UTILITY_H
#include <cstddef>
#include <cstdlib>
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#endif
main.cpp
/*-----------------------------------------------
Created By EverSteins
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#include "stdafx.h"
#include "stack.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Stack s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.Push(4);
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
cin.get();
return 0;
}