C++实现 栈和队列

#栈是一种先进后出的数据结构,而队列是一种先进先出的数据结构
栈是由Top来指向栈顶元素,通过压栈和出栈来存储数据,主要是pop和push两个函数。
栈由于其独特的存储方式,适合在一些特别环境下使用,栈可以用来当作计算数据存储结构。

class Stack
{
    TYPE *dat;
    int top;
    int cap;
public:
    Stack(int size)
    {   
        cap = size;
        dat = new TYPE[cap];
        top = -1; 
    }   
    bool empty(void)
    {   
        if(top == -1) return true;
        return false;
    }   
    bool full(void)
    {   
        if(top == (cap-1)) return true;
        return false;
    }   
   TYPE  pop(void)
    {
        if(empty()) return false;
        TYPE num = dat[top];
        top--;
        return num;

    }
    bool push(TYPE val)
    {
        if(full()) return false;
        top++;
        dat[top] = val;
        return true;
    }
  ~Stack(void)
    {
        while(pop());
        delete[] dat;
    }


##队列
队列是作为一种先进先出的数据的结构,这里介绍顺序队列,通过数组模拟循环队列存储方式
循环队列的特点:不会浪费存储空间,节约内存,但是依然存在数据不确定下的上溢或者浪费,但和顺序队列相比算是一种进步。

typedef struct Queu
{
	TYPE* ptr;
	size_t cap;
	int head;
	int tail;
}Queue;

Queue* creat_queue(size_t cap)
{
	Queue* queue = new Queue;
	queue->ptr = new TYPE[cap+1];
	queue->cap = cap+1;
	queue->head = 0;
	queue->tail = -1;
	return queue;
}
void del_queue(Queue* q)
{
	delete[] q->ptr;
	delete q;
}
bool empty(Queue* q)
{
	if((q->tail+1) %q->cap == q->head) return true;
	else return false;
}
bool full(Queue* q)
{
	if((q->tail+2) %q->cap == q->head) return true;
	else return false;
}
bool in_queue(Queue* q,TYPE val)
{
	if(full(q)) return false;
	q->tail = (q->tail+1) % q->cap;
	q->ptr[q->tail] = val;
	return true;
}
bool out_queue(Queue* q)
{
	if(empty(q)) return false;
	q->head = (q->head+1) %q->cap;
	return true;
}
TYPE* head_queue(Queue* q)
{
	if(empty(q)) return NULL;
	return q->ptr+q->head;
}

TYPE* tail_queue(Queue* q)
{
	if(empty(q)) return NULL;
	return q->ptr+q->tail;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值