剑指 Offer 06. 从尾到头打印链表
https://leetcode-cn.com/leetbook/read/illustrate-lcof/xs92sh/
- 方法一:reverse()
var reversePrint = function(head) {
var stack = [];
while(head != null){
stack.push(head.val);
head = head.next
}
//return stack.reverse()
};
- 方法二:栈(先进后出,push+pop)
var reversePrint = function(head) {
var stack = [];
while(head != null){
stack.push(head.val);
head = head.next;
}
var res = [];
const len = stack.length; //需要初始stack的长度
for(var i = 0; i< len; i++){
res.push(stack.pop()); //stack长度会不断变化
}
return res;
};
剑指 Offer 09. 用两个栈实现队列
https://leetcode-cn.com/leetbook/read/illustrate-lcof/xz8cid/
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==0){
while(this.stack1.length != 0){
this.stack2.push(this.stack1.pop())
}
}
if(this.stack2.length==0){
return -1
}else {
return this.stack2.pop()
}
};
剑指 Offer 30. 包含 min 函数的栈
https://leetcode-cn.com/leetbook/read/illustrate-lcof/xzqg03/
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack1 = [];
this.stack2 = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack1.push(x);
if(this.stack2.length == 0 || this.stack2[this.stack2.length - 1] >= x) {
this.stack2.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if(this.stack1.pop() == this.stack2[this.stack2.length - 1]) {
this.stack2.pop();
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack1[this.stack1.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.stack2[this.stack2.length - 1];
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.min()
*/