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

来源:互联网 发布:数据交换平台etl 编辑:程序博客网 时间:2024/06/10 02:37

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; }

0 0
原创粉丝点击