stack.h
/*-----------------------------------------------
Created By EverSteins
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#ifndef QUEUE_H
#define QUEUE_H
#include "utility.h"
typedef int ElemType;
class LinkStack
{
public:
LinkStack():count_(0),top_node_(NULL){}
~LinkStack();
bool Empty() const //内联
{
return count_ == 0;
}
size_t Size() const //内联
{
return count_;
}
bool Top(ElemType &entry) const;
void Push(const ElemType &entry); //记得count++
bool Pop(); //记得count--,并释放空间
void ShowALLEntry() const;
private:
struct Node
{
ElemType entry_;
Node *next_;
Node(const ElemType &entry,Node *next):entry_(entry),next_(next){}
};
DISALLOW_COPY_AND_ASSIGN(Queue); //在utility.h中定义,为了禁用拷贝和赋值构造函数
size_t count_;
Node *top_node_;
};
#endif
stack.cpp
/*-----------------------------------------------
Created By EverSteins
Email:EverSteins@gmail.com
转载请注明出处
------------------------------------------------*/
#include "stdafx.h"
#include "utility.h"
#include "stack.h"
#include <iostream>
using namespace std;
LinkStack::~LinkStack()
{
while (!Empty())
{
Pop();
}
}
bool LinkStack::Top(ElemType &entry) const
{
if (Empty())
return false;
entry=top_node_->entry_;
return true;
}
void LinkStack::Push(const ElemType &entry)
{
Node *new_node=new Node(entry,top_node_);
top_node_=new_node;
count_++; //不要忘了
}
bool LinkStack::Pop()
{
if (Empty())
return false;
Node *next_node=top_node_->next_;
delete top_node_;
top_node_=next_node;
count_--; //不要忘了
return true;
}
void LinkStack::ShowALLEntry() const
{
Node *tmp_node=top_node_;
while (tmp_node != NULL)
{
cout<<tmp_node->entry_<<' ';
tmp_node = tmp_node->next_;
}
cout<<endl;
}
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[])
{
LinkStack s1;
s1.Push(1);
s1.Push(2);
s1.Push(3);
s1.ShowALLEntry();
s1.Pop();
s1.Pop();
s1.Pop();
s1.Pop();
cin.get();
return 0;
}