欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

l4 使用栈(先进后出)来实现队列(先进先出)的功能

程序员文章站 2022-03-14 15:05:51
...
#include <iostream>
#include <stack>
#include <queue>

class CQueue {
public:
    CQueue(void);
    ~CQueue();
    
    void appendTail(int node);
    int deleteHeader();
    
private:
    std::stack<int> * stack1;
    std::stack<int> * stack2;
};

CQueue::CQueue(void) {
    stack2 = new std::stack<int>;
    stack1 = new std::stack<int>;
}

CQueue::~CQueue() {
    delete stack1;
    delete stack2;
}

void CQueue::appendTail(int node) {
    stack1->push(node);
}

int CQueue::deleteHeader() {
    if (stack2->empty()) {
        while (!stack1->empty()) {
            int tmp = stack1->top();
            stack2->push(tmp);
            stack1->pop();
        }
    }
    
    if (stack2->empty()) {
        printf("queue is empty");
        return -1;
    } else {
        int returnValue = stack2->top();
        stack2->pop();
        return returnValue;
    }
}

int main () {
    CQueue *queue = new CQueue();
    for (int i = 0; i < 10; i++) {
        queue->appendTail(i);
    }
    
    for (int i = 0; i < 10; i++) {
       int result = queue->deleteHeader();
        printf("%d",result);
    }
}