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

#include 
#include 
#include 

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

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

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

你可能感兴趣的:(l4 使用栈(先进后出)来实现队列(先进先出)的功能)