c/c++栈与队的数组实现方法

本文介绍如何使用数组容器实现栈(stack)与队列(queue)的基本操作。包括创建、销毁、压入、弹出元素等,并提供了完整的类定义及成员函数实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

stack与queue均为容器适配器,下面使用数组容器实现栈和队的基本操作:

stack:

class stack {
private:
  int * storage;
  int max_size;
  int top;
public:
  stack() {
    this->storage = new int[MAX_SIZE]();
    this->max_size = MAX_SIZE;
    this->top = -1;
  }
  ~stack() {
    delete []this->storage;
  }
  void push(int);
  void pop(void);
  int peek(void);
  bool isEmpty(void);
  bool isFull(void);
  void clear(void);
};
void stack::push(int data) {
  if (this->isFull()) {
    return;
  }
  this->top++;
  this->storage[top] = data;
}
 
void stack::pop(void) {
  if (this->isEmpty()) {
    return;
  }
  this->top--;
}
int stack::peek(void) {
  if (this->isEmpty()) {
    return 0;
  }
  return storage[top];
}
 
bool stack::isEmpty(void) { return (this->top == -1); }
 
bool stack::isFull(void) { return (this->top + 1 >= this->max_size); }
 
void stack::clear(void) { this->top = -1; }



queue:
class queue {
private:
  int * storage;
  int max_size;
  int head;
  int rear;
public:
  queue() {
    // notice the capability is still MAX_SIZE
    this->storage = new int[MAX_SIZE+1]();
    this->max_size = MAX_SIZE+1;
    this->head = 0;
    this->rear = 0;
  }
  ~queue() {
    delete []storage;
  }
  void push(int);
  void pop(void);
  int front(void);
  int back(void);
  bool isFull(void);
  bool isEmpty(void);
  void clear(void);
};
void queue::push(int data) {
  if (this->isFull()) {
    return;
  }
  this->storage[rear] = data;
  this->rear = (this->rear + 1) % this->max_size;
}
 
void queue::pop(void) {
  if (this->isEmpty()) {
    return;
  }
  this->head = (this->head + 1) % this->max_size;
}
 
int queue::front(void) {
  if (this->isEmpty()) {
    return 0;
  }
  return this->storage[head];
}
 
int queue::back(void) {
  if (this->isEmpty()) {
    return 0;
  }
  return this->storage[(rear-1+max_size) % max_size];
}
 
bool queue::isFull(void) {
  return ((this->rear + 1) % this->max_size) == this->head;
}
 
bool queue::isEmpty(void) { return this->head == this->rear; }
 
void queue::clear(void) { this->rear = this->head; }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值