# 前端力扣刷题_数据结构篇（队列&栈）

``````var CQueue = function() {
//用两个栈实现队列，所以要创建两个栈
this.stack1=[];//stack1相当于茶壶
this.stack2=[];//stack2相当于茶杯
};

/**
* @param {number} value
* @return {void}
*/
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value);
};

/**
* @return {number}
*/
//我们喝水是从杯子里喝，所以先检查杯子有没水，杯子有水，直接从杯子喝；杯子没水了，再看看茶壶里有没有，有就再全部倒进//去。这时茶壶底下的水就倒到了杯子上面， 然后从杯子上面开始喝。
if(this.stack2.length===0){//杯子没水
if(this.stack1.length===0){//茶壶也没水
return -1;
}
while(this.stack1.length!==0){//while茶壶有水
this.stack2.push(this.stack1.pop());把茶壶的水倒进杯子里
}
}
return this.stack2.pop();//杯子有水直接喝
};
``````

``````var MyQueue = function() {
this.stack1=[];//茶壶
this.stack2=[];//茶杯
};

/**
* @param {number} x
* @return {void}
*/
MyQueue.prototype.push = function(x) {
this.stack1.push(x);
};

/**
* @return {number}
*/
MyQueue.prototype.pop = function() {
if(this.stack2.length===0){
while(this.stack1.length!==0){
this.stack2.push(this.stack1.pop());
}
}
return this.stack2.pop();
};

/**
* @return {number}
*/
MyQueue.prototype.peek = function() {
if(this.stack2.length===0){
while(this.stack1.length!==0){
this.stack2.push(this.stack1.pop());
}
}
return this.stack2[this.stack2.length-1];
};

/**
* @return {boolean}
*/
MyQueue.prototype.empty = function() {
return this.stack1.length===0&&this.stack2.length===0;
};
``````

``````var MinStack = function() {
this.x_stack = [];
this.min_stack = [Infinity];
};

MinStack.prototype.push = function(x) {
this.x_stack.push(x);
this.min_stack.push(Math.min(this.min_stack[this.min_stack.length - 1], x));
};

MinStack.prototype.pop = function() {
this.x_stack.pop();
this.min_stack.pop();
};

MinStack.prototype.top = function() {
return this.x_stack[this.x_stack.length - 1];
};

MinStack.prototype.getMin = function() {
return this.min_stack[this.min_stack.length - 1];
};
``````

``````function IsPopOrder(pushV, popV)
{
let stack=[];
let index=0;//初始化
for(let node of pushV){
stack.push(node);//压入栈
while(stack.length!==0&&stack[stack.length-1]===popV[index]){//栈顶元素等于popV[index]
stack.pop();//弹出栈
index+=1;//index+=1
}
}
return stack.length===0? true : false;
}
``````

``````function ReverseSentence(str)
{
return str.split(' ').reverse().join(' ');
}
``````

``````var isValid = function(s) {
const obj={')':'(','}':'{',']':'['};
const stack=[];
for(let p of s){
if(obj[p]){
if(stack.pop()!==obj[p]) return false;
}else{
stack.push(p);
}
}
return stack.length===0;
};
``````

``````var removeDuplicates = function(s) {
const stack=[];
for(let char of s){
if(stack.length!==0&&stack[stack.length-1]===char){
stack.pop();
}else{
stack.push(char);
}
}
return stack.join('');
};
``````