章節連結
堆疊式一個遵循LIFO(Left In First Out)後進先出的原則。在現實中就有點像是堆在桌上的書,越上方的(後放)會越先被拿走。不過 JavaScript 並沒有內建這樣的資料結構,但可以用 array 陣列的方法來達成。
指令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
/*Stack*/ function Stack(){ var items = [] this.push = function(element){ return items.push(element) } this.pop = function(){ return items.pop() } this.peek = function(){ return items[items.length-1] } this.isEmpty = function(){ return items.length === 0 } this.size = function(){ return items.length } this.clear = function(){ return items = [] } this.print = function(){ console.log(items.toString()) } } // 10 進位轉 2 進位 function decTobin(decNum){ let stack = new Stack() let temp = 0 let binary = '' while(decNum>0){ temp = Math.floor(decNum%2) stack.push(temp) decNum = Math.floor(decNum/2) } while(!stack.isEmpty()){ binary += stack.pop().toString() } return binary } // 10 進位轉 N 進位 (最多到16進位) function baseConverter(decNum, base){ let stack = new Stack() let temp = 0 let result = '' let digits = '0123456789ABCDEF' while(decNum>0){ temp = Math.floor(decNum%base) stack.push(temp) decNum = Math.floor(decNum/base) } while(!stack.isEmpty()){ result += digits[stack.pop()] } return result } console.log(baseConverter(100,2)) console.log(baseConverter(100,4)) console.log(baseConverter(100,8)) console.log(baseConverter(100,10)) console.log(baseConverter(100,16)) |
LeetCode 練習記錄
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// 225. Implement Stack using Queues https://leetcode.com/problems/implement-stack-using-queues/ var MyStack = function() { items = [] }; MyStack.prototype.push = function(x) { return items.push(x) }; MyStack.prototype.pop = function() { return items.pop() }; MyStack.prototype.top = function() { return items[items.length-1] }; MyStack.prototype.empty = function() { return items.length === 0 ? true : false }; /** * Your MyStack object will be instantiated and called as such: * var obj = new MyStack() * obj.push(x) * var param_2 = obj.pop() * var param_3 = obj.top() * var param_4 = obj.empty() */ |