栈和队列的区别
- 栈:先进后出(First In Last Out )FILO
2. 队列:先进先出(First In First Out)FIFO
1.使用两个栈模拟队列
https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
思路:双栈
解题思路
stackA负责存储数据,stackB负责弹出数据
存数据的时候,往A里面存
取数据的时候,先判断B有没有值,如果有值直接pop。
如果B没值,就从A里面取。
都没值,返回-1
var CQueue = function() {this.stackA = []this.stackB = []};/*** @param {number} value* @return {void}*/CQueue.prototype.appendTail = function(value) {this.stackA.push(value)};/*** @return {number}*/CQueue.prototype.deleteHead = function() {if(!this.stackB.length) {if (!this.stackA.length) {return -1} else {while(this.stackA.length){this.stackB.push(this.stackA.pop())}}}return this.stackB.pop()};/*** Your CQueue object will be instantiated and called as such:* var obj = new CQueue()* obj.appendTail(value)* var param_2 = obj.deleteHead()*/
2.包含min函数最小的栈
思路:了解什么是真正的栈
/**
* * 题目名称:包含min函数最小的栈
* * 题目地址:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/
*/
// * 思路:
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.stack = []
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.stack.push(x)
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
return this.stack.pop()
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length-1]
};
/**
* @return {number}
*/
MinStack.prototype.min = function() {
return Math.min(...this.stack)
};
/**
* 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()
*/
// 测试用例
let minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3); // 栈 [-2,0,-3]
console.log(minStack.min())//--> 返回 -3(最小值用Math.min方法,然后把数组展开放进去)
console.log(minStack.pop()) //--> 返回 -3 ,返回要最先出栈的数,因为先进后出,第一个元素就是pop(弹出数组最后一个数)
console.log(minStack.top())// --> 返回 0 ,返回然后要出栈的数(数组的最后一项)
console.log(minStack.min())//--> 返回 -2
3.输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] (是一个链表)输出:[2,3,1]
/**
* @param {ListNode} head
* @return {number[]}
*/
var reversePrint = function(head) {
const res = []
// while或者递归查看是不是还有一项,如果有就赋值,存到数组中
while (head) {
res.push(head.val)
head = head.next
}
return res.reverse()
};
