栈是FILO结构,而队列是FIFO的结构。
使用两个栈,一个用于正常的操作,一个用于遍历访问。通过再次逆向访问得到正向的访问结果。难度比较简单。
#include <string>
#include <list>
#include <iostream>
#include <vector>
using namespace std;
typedef struct {
int values[10000];
int tail;
} my_stack;
static my_stack stack_enter;//用于接收外部输入的栈A。只输入时压栈。
static my_stack stack_pop; // 访问缓存栈B。出栈时,为空时再把此时栈A所有数据依次出栈后进入栈B。访问只>从栈B弹出
class CQueue {
public:
CQueue() {
//reset stack
stack_enter.tail = -1;
stack_pop.tail = -1;
}
void appendTail(int value) {
stack_enter.values[++stack_enter.tail] = value;
}
int deleteHead() {
if (stack_pop.tail < 0) {
// 栈B为空,尝试从栈A冒出所有元素
if (stack_enter.tail < 0) {
return -1;
}
while (stack_enter.tail >= 0) {
stack_pop.values[++stack_pop.tail] = stack_enter.values[stack_enter.tail--];
}
}
return stack_pop.values[stack_pop.tail--];
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/
int main()
{
CQueue* obj = new CQueue();
cout << obj->deleteHead() << endl;
obj->appendTail(5);
obj->appendTail(2);
cout << obj->deleteHead() << endl;
cout << obj->deleteHead() << endl;
cout << obj->deleteHead() << endl;
system("pause");
return 0;
}
评论 (0)