0%

代码随想录第二十七天

字符串-用栈实现队列

题目链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {

}

void push(int x) {
stIn.push(x);
}

int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;

}

int peek() {
int result = this->pop();//直接复用前面的pop函数,记得pop后要保存
stOut.push(result);
return result;
}

bool empty() {
return stOut.empty() && stIn.empty();
}
};

/**
* 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();
* bool param_4 = obj->empty();
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
typedef struct {
int stInTop, stOutTop;
int stIn[100],stOut[100];
} MyQueue;


MyQueue* myQueueCreate() {
MyQueue* queue = (MyQueue*)malloc(sizeof(MyQueue));
queue->stInTop = 0;
queue->stOutTop = 0;
return queue;
}

void myQueuePush(MyQueue* obj, int x) {
obj->stIn[(obj->stInTop)++] = x;
}

int myQueuePop(MyQueue* obj) {
int stInTop = obj->stInTop;
int stOutTop = obj->stOutTop;
if(stOutTop == 0){
while(stInTop > 0)obj->stOut[stOutTop++] = obj->stIn[stInTop];
}

int top = obj->stOut[--stOutTop];

while(stOutTop > 0)obj->stIn[stInTop++] = obj->stOut[--stOutTop];

obj->stInTop = stInTop;
obj->stOutTop = stOutTop;

return top;

}

int myQueuePeek(MyQueue* obj) {
return obj->stIn[0];
}

bool myQueueEmpty(MyQueue* obj) {
return obj->stInTop == 0 && obj->stOutTop == 0;
}

void myQueueFree(MyQueue* obj) {
obj->stInTop = 0;
obj->stOutTop = 0;
}

/**
* Your MyQueue struct will be instantiated and called as such:
* MyQueue* obj = myQueueCreate();
* myQueuePush(obj, x);

* int param_2 = myQueuePop(obj);

* int param_3 = myQueuePeek(obj);

* bool param_4 = myQueueEmpty(obj);

* myQueueFree(obj);
*/