棧是一種先進后出的特殊線性表結構,存儲上分鏈式存儲和順序存儲兩種方式
鏈式存儲:
function LinkedStack() { let Node = function (ele) { this.ele = ele; this.next = null; } let length = 0, top; //棧頂指針 //壓棧操作 this.push = function (ele) { let node = new Node(ele); top ? node.next = top : top = node; top = node; length++; return true; } //退棧操作 this.pop = function () { let current = top; if (top) { top = current.next; current.next = null; length--; return current; } else { return 'null stack'; } } this.top = function () { return top; } this.size = function () { return length; } //toString 從棧頂到棧底 this.toString = function () { let string = ''; current = top; while (current) { string += current.ele + ' '; current = current.next; } return string; } this.clear = function () { top = null; length = 0; return true; } } //使用 let myStack = new LinkedStack(); myStack.push('1') myStack.push('2') myStack.push('3') myStack.push('4') console.log(myStack.toString()) // 4 3 2 1 myStack.pop() console.log(myStack.toString()) // 3 2 1 myStack.pop() myStack.pop() console.log(myStack.pop()) // Node { ele: '1', next: null } console.log(myStack.pop()) // null stack
順序存儲:用js內置對象Array實現
function ArrayStack(){ var arr = []; //壓棧操作 this.push = function(element){ arr.push(element); } //退棧操作 this.pop = function(){ return arr.pop(); } //獲取棧頂元素 this.top = function(){ return arr[arr.length-1]; } //獲取棧長 this.size = function(){ return arr.length; } //清空棧 this.clear = function(){ arr = []; return true; } this.toString = function(){ return arr.toString(); } }