C++ 实现栈的基本数据结构和操作
#include
using namespace std;
#define MaxSize 50//定义最大常数值
typedef int Elemtype;
typedef struct
{
Elemtype data[MaxSize];
int top;//栈顶元素,即存放栈顶元素在data数组中的下标
} SqStack;//顺序栈类型
void InitStack(SqStack*& s)
{
s = new SqStack;//分配一个顺序栈空间
s->top = -1;//栈顶指针置为-1
}
void DestroyStack(SqStack *&s)
{
delete s;
}
bool stackempty(SqStack* s)
{
return s->top == -1;
}
bool push(SqStack*& s, Elemtype e)
{
if (s->top == MaxSize - 1)//当栈满的时候溢出
return false;
s->top++;//栈顶指针加一
s->data[s->top] = e;//元素e放置于栈顶指针处
return true;
}
bool pop(SqStack*& s, Elemtype& e)
{
if (s->top == -1)//当栈为空返回假
return false;
e = s->data[s->top];
s->top--;
return true;
}
bool GetTop(SqStack* s, Elemtype& e)
{
if (s->top == -1)
return false;
e = s->data[s->top];
return true;
}
typedef struct
{
Elemtype data[MaxSize];
int front, rear;//队头和队尾指针
} SqQueue;//顺序队类型
void InitQueue(SqQueue*& q)
{
q = new SqQueue;
q->front = q->rear = -1;//队空的条件 q->front == q->rear,这里置初始值
}
void destroyqueue(SqQueue*& q)
{
delete q;
}
bool QueueEmpty(SqQueue* q)
{
return q->front == q->rear;
}
bool enQueue(SqQueue*& q, Elemtype e)
{
if (q->rear == MaxSize - 1)//队满溢出
return false;
q->rear++;
q->data[q->rear] = e;
return true;
}
bool deQueue(SqQueue*& q, Elemtype& e)
{
if (q->front == q->rear)
return false;
q->front++;
e = q->data[q->front];//注意front指向的第一个元素的前面一个元素
return true;
}
int main()
{
}