使用js棧stack類的實現
/*使用棧stack類的實現*/ function stack() { this.dataStore = [];//保存棧內元素,初始化為一個空數組 this.top = 0;//棧頂位置,初始化為0 this.push = push;//入棧 this.pop = pop;//出棧 this.peek = peek;//查看棧頂元素 this.clear = clear;//清空棧 this.length = length;//棧內存放元素的個數 } function push(element){ this.dataStore[this.top++] = element; } function pop(){ return this.dataStore[--this.top]; } function peek(){ return this.dataStore[this.top-1]; } function clear(){ this.top = 0; } function length(){ return this.top; } /*測試stack類的實現*/ var s = new stack(); s.push("aa"); s.push("bb"); s.push("cc"); console.log(s.length());//3 console.log(s.peek());//cc var popped = s.pop(); console.log(popped);//cc console.log(s.peek());//bb
