# 题目描述
用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail
和 deleteHead
,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead
操作返回 -1 )
提示:
1 <= values <= 10000
- 最多会对
appendTail
、deleteHead
进行10000
次调用
# 测试用例
用例1:
- 输入:
["CQueue","appendTail","deleteHead","deleteHead","deleteHead"]
[[],[3],[],[],[]]
- 输出:
[null,null,3,-1,-1]
用例2:
- 输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
- 输出:
[null,-1,null,null,5,2]
# 思路
instack
栈放入数据[1, 2, 3]
,outstack
输出数据
输出时先看outStack
有没有,有就outStack.pop()
,没有就把inStack
中的内容放到outStack
,然后输出outStack.pop()
# 代码实现
var CQueue = function() {
// const inStack = [];
// const outStack = [];
this.inStack = [];
this.outStack = [];
};
// instack栈放入数据 [1, 2, 3]
// outstack 输出数据
// 输出时先看outStack有没有
// 有就outStack.pop
// 没有就把inStack中的内容放到outStack,然后输出outStack
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.inStack.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if(this.inStack.length == 0 && this.outStack.length == 0){
return -1;
}
if(this.outStack.length > 0){
return this.outStack.pop();
}
else{
while(this.inStack.length > 0){
this.outStack.push(this.inStack.pop());
}
return this.outStack.pop();
}
};
/**
* Your CQueue object will be instantiated and called as such:
* var obj = new CQueue()
* obj.appendTail(value)
* var param_2 = obj.deleteHead()
*/
var obj = new CQueue()
console.log("初始化: ", obj);
obj.appendTail(3);
console.log("obj_1: ", obj);
obj.appendTail(4);
obj.appendTail(54);
obj.appendTail(34);
obj.appendTail(24);
console.log("obj_2: ", obj);
var test = obj.deleteHead();
console.log("test: ", test);
var test = obj.deleteHead();
console.log("test: ", test);
var test = obj.deleteHead();
console.log("test: ", test);
var test = obj.deleteHead();
console.log("test: ", test);
var test = obj.deleteHead();
console.log("test: ", test);
var test = obj.deleteHead();
console.log("test: ", test);
console.log("obj_3: ", obj);
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76