堆栈是一种特殊的线性表,因此也可以分为顺序存储和链式存储。队列最突出的特点是先进后出。
一、顺序存储
新建一个类Stack,在Stack.h中:
using namespace std;
#define ElementType int
#define Maxsize 1024
class Stack
{
public:
Stack();
~Stack();
void Push(ElementType item);
ElementType Pop();
private:
ElementType Data[Maxsize];
int Top;
};
在Stack.cpp中:
#include "Stack.h"
Stack::Stack()
{
Top = -1; //代表无数据
}
Stack::~Stack()
{
}
void Stack::Push(ElementType item)
{
if (Top == Maxsize - 1)
cout << "error\n";
else
Data[++Top] = item;
}
ElementType Stack::Pop()
{
if (Top == -1) return -1;
else return (Data[Top--]);
}
在main.cpp中:
#include"Stack.h"
int main()
{
Stack S;
S.Push(1); S.Push(2); S.Push(3); S.Push(4);
cout << S.Pop() << "\n";
cout << S.Pop() << "\n";
S.Push(8);
cout << S.Pop() << "\n";
system("pause");
return 0;
}
运行结果:
二、链式存储
新建一个类Stack,在Stack.h中:
#include"iostream"
using namespace std;
#define ElementType int
class SNode
{
public:
ElementType Data;
SNode * Next;
};
class Stack
{
public:
Stack();
~Stack();
void Push(ElementType item);
bool IsEmpty();
ElementType Pop();
private:
SNode * SPtr;
};
在Stack.cpp中:
#include "Stack.h"
Stack::Stack()
{
SPtr = new SNode;
}
Stack::~Stack()
{
}
bool Stack::IsEmpty()
{
return (SPtr->Next == NULL);
}
void Stack::Push(ElementType item)
{
SNode * TmpCell = new SNode;
TmpCell->Data = item;
TmpCell->Next = SPtr->Next;
SPtr->Next = TmpCell;
}
ElementType Stack::Pop()
{
SNode * FistCell = new SNode;
ElementType Tmp;
if (IsEmpty()) return NULL;
else
{
FistCell = SPtr->Next;
SPtr->Next = FistCell->Next;
Tmp = FistCell->Data;
delete FistCell;
return Tmp;
}
}
在main.cpp中:
#include"Stack.h"
int main()
{
Stack S;
S.Push(4); S.Push(3); S.Push(7); S.Push(5);
cout << S.Pop() << "\n";
cout << S.Pop() << "\n";
S.Push(8);
cout << S.Pop() << "\n";
system("pause");
return 0;
}
运行结果: