*9 用栈实现队列
var CQueue = function() {
this.stack0 = [];
this.stack1 = [];
};
/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
while(this.stack1.length!==0){
this.stack0.push(this.stack1.pop())
}
this.stack0.push(value);
};
/**
* @return {number}
*/
CQueue.prototype.deleteHead = function() {
if(this.stack0.length===0) return -1;
while(this.stack0.length!==0){
this.stack1.push(this.stack0.pop());
}
let res = this.stack1.pop();
while(this.stack1.length!==0){
this.stack0.push(this.stack1.pop())
}
return res;
};
30.包含min函數的栈
var MinStack = function() {
this.stack = [];
this.min_stack = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x);
if(this.min_stack.length===0) this.min_stack.push(x);
else {
this.min_stack.push(Math.min(this.min_stack[this.min_stack.length-1],x));
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack.pop();
this.min_stack.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return this.min_stack[this.min_stack.length-1]
};
06.从尾到头打印链表
var reversePrint = function(head) {
let res = [];
while(head!==null){
res.unshift(head.val);
head = head.next;
}
return res;
};
24.翻转链表
var reverseList = function(head) {
if(head===null||head.next===null) return head;
return reverse(null, head);
};
var reverse = (pre, next)=>{
if(next===null) return pre;
let tmp = next.next;
next.next = pre;
return reverse(next, tmp);
}