- 图解
outStack.push(inStack.pop());
C代码:双栈
typedef struct {
int* stk; // 数组指针,指向栈内的元素
int stkSize;
int stkCapacity;
} Stack; // 封装一个栈的结构体(数组指针、下标、内存大小)
Stack* stackCreate(int cpacity) { // 创建栈:一个结构体指针、初始化数组内存、下标
Stack* ret = (Stack*)malloc(sizeof(Stack));
ret->stk = (int*)malloc(sizeof(int) * cpacity);
ret->stkSize = 0;
ret->stkCapacity = cpacity;
return ret;
}
void stackPush(Stack* obj, int x) {
obj->stk[obj->stkSize++] = x;
}
void stackPop(Stack* obj) {
obj->stkSize--;
}
int stackTop(Stack* obj) {
return obj->stk[obj->stkSize - 1];
}
bool stackEmpty(Stack* obj) {
return obj->stkSize == 0;
}
void stackFree(Stack* obj) {
free(obj->stk); // 释放数组内存
}
typedef struct { // 双栈
Stack* inStack;
Stack* outStack;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* ret = (MyQueue*)malloc(sizeof(MyQueue)); // 创建一个双栈的指针
ret->inStack = stackCreate(100); // 创建双栈的内存
ret->outStack = stackCreate(100);
return ret;
}
void in2out(MyQueue* obj) {
while (!stackEmpty(obj->inStack)) {
stackPush(obj->outStack, stackTop(obj->inStack));
stackPop(obj->inStack);
}
}
void myQueuePush(MyQueue* obj, int x) {
stackPush(obj->inStack, x);
}
int myQueuePop(MyQueue* obj) { // 从outStack中删除元素
if (stackEmpty(obj->outStack)) {
in2out(obj); // 把inStack中的元素全部倒入outStack
}
int x = stackTop(obj->outStack);
stackPop(obj->outStack);
return x;
}
int myQueuePeek(MyQueue* obj) { // 从outStack中返回元素
if (stackEmpty(obj->outStack)) {
in2out(obj); // 用到obj的inStack、outStack栈指针;
}
return stackTop(obj->outStack);
}
bool myQueueEmpty(MyQueue* obj) {
return stackEmpty(obj->inStack) && stackEmpty(obj->outStack);
}
void myQueueFree(MyQueue* obj) {
stackFree(obj->inStack); // 传栈结构体指针
stackFree(obj->outStack);
}
Java代码:
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
class MyQueue { //java
Deque<Integer> inStack;
Deque<Integer> outStack;
public MyQueue() {
inStack = new ArrayDeque<Integer>();
outStack = new ArrayDeque<Integer>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.pop();
}
public int peek() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.peek();
}
public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}
private void in2out() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop()); //巧妙啊!
}
}
}