栈是一种遵从后进先出(LIFO)原则的有序集合。新添加的或待删除的元素都保存在栈末尾,称作栈顶,另一端称作栈底。在栈里,新元素都靠近栈顶,旧元素就接近栈底。
队列是遵循先进先出(FIFO)原则的一组有序的项。队列在尾部添加新元素,并从顶部移除元素。最新添加的元素必须排在队列的末尾。
//创建一个类来表示栈
function Stack(){
var items=[];//保存栈里的元素
this.push=function(e){//添加一个元素到栈顶
items.push(e);
}
this.pop=function(e){//弹出并返回栈顶元素
return items.pop();
}
this.isEmpty=function(){//如果栈里没有任何元素就返回true,否则返回false
return items.length==0;
}
this.peek=function(){//返回栈顶元素
return items[items.length-1];
}
this.mylength=function(){//返回栈里的元素个数
return items.length;
}
this.clear=function(){//清除栈里的元素
items=[];
}
this.print=function(){//打印栈里的元素
console.log(items);
}
}
var stack=new Stack();//实例化一个对象
stack.push(4);
stack.push('a');
stack.push('cde');
stack.print();//[4,'a','cde']
console.log(stack.peek());//cde
console.log(stack.mylength());//3
while(!stack.isEmpty()){
console.log(stack.pop());
//cde
//a
//4
}
stack.push('abc');
stack.clear();
stack.print();//[]
//创建一个类来表示队列
function Queue(){
var items=[];//保存队列里的元素
this.enqueue=function(e){//添加一个元素到队列尾部
items.push(e);
}
this.dequeue=function(){//移除队列的第一项,并返回
return items.shift();
}
this.front=function(){//返回队列的第一项
return items[0];
}
this.isEmpty=function(){//如果队列中部包含任何元素,返回true,否则返回false
return items.length==0;
}
this.mylength=function(){//返回队列包含的元素个数
return items.length;
}
this.clear=function(){//清除队列中的元素
items=[];
}
this.print=function(){//打印队列中的元素
console.log(items);
}
}
var queue=new Queue();//实例化一个对象
queue.enqueue(1);
queue.enqueue('a');
queue.enqueue('bcd');
queue.print();//[1,'a','bcd']
console.log(queue.mylength());//3
console.log(queue.front());//1
while(!queue.isEmpty()){
console.log(queue.dequeue());
//1
//a
//bcd
}
queue.enqueue('a');
queue.clear();
queue.print();//[]