C++ 实现栈的基本数据结构和 *** 作

C++ 实现栈的基本数据结构和 *** 作,第1张

C++ 实现栈的基本class="superseo">数据结构和 *** 作
#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()
{
   
}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/914781.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存