1. 程式人生 > >js資料結構之棧和佇列

js資料結構之棧和佇列

棧是一種遵從後進先出(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();//[]