-
Notifications
You must be signed in to change notification settings - Fork 644
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
腾讯&剑指offer09:用两个栈实现队列 #34
Comments
var CQueue = function() {
this.stack1 = []
this.stack2 = []
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if (this.stack2.length) {
return this.stack2.pop();
} else if (this.stack1.length) {
while(this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
return this.stack2.pop();
} else {
return -1
}
}; |
解题思路:
代码实现: const CQueue = function() {
this.stack1 = []
this.stack2 = []
};
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value)
};
CQueue.prototype.deleteHead = function() {
if(this.stack2.length) {
return this.stack2.pop()
}
if(!this.stack1.length) return -1
while(this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
return this.stack2.pop()
}; 复杂度分析:
|
var CQueue = function() {
this.s = [];
this.t = [];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.s.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if (this.t.length > 0) {
return this.t.pop();
} else {
while (this.s.length > 0) {
this.t.push(this.s.pop());
}
if (this.t.length > 0) {
return this.t.pop();
}
}
return -1;
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数
appendTail
和deleteHead
,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead
操作返回-1
)示例 1:
示例 2:
提示:
1 <= values <= 10000
appendTail
、deleteHead
进行10000
次调用leetcode
The text was updated successfully, but these errors were encountered: