javascript实现堆栈和简单的应用

xiaoxiao2021-02-28  97

堆栈数据结构的实现:

在编程方式上面采用了面向对象编程里面的组合使用构造函数模式和原型模式; 实现原理:这里就不阐述堆栈的基本概念了,学c语言数据结构的时候都学过吧,这里主要纪录一下用js实现的原理;c语言用结构体去实现,在js语言中用面向对象就十分方便了;

用dataStore存储数据;用top表示栈顶位置,它的值也等于栈的长度;出栈和入栈方法分别是pop和push;show()方法返回某一个位置的值 - function Stack(){ //存放数据 this.dataStore = []; // 纪录栈顶的位置 this.top = 0; } Stack.prototype = { // 出栈 push: function(value){ this.dataStore[this.top ++] = value; }, // 入栈 pop: function(){ if (this.top > 0){ return this.dataStore[-- this.top]; } else { alert("亲:已经到栈顶了,不能弹出栈了"); } }, // 数组长度 length: function(){ return this.top; }, // 展示当前位置的值 show: function(index){ if (index <= this.top && index > 0){ return this.dataStore[index - 1]; } else { alert("警告:请求输出的值超出栈顶或者小于0"); } } }

堆栈实现进制转换

实现原理: step1: 新建一个堆栈 step2:把值除基数的余数压入栈 step3:更新number值为Math.floor(number / base) step4:挨个出栈,拼接成字符串形式 代码:

function convert(number, base){ var stack2 = new Stack(); while (number > 0){ stack2.push(number % base); number = Math.floor(number / base); } var length = stack2.top; var str = ''; for (var i = 0; i < length; i++){ str += stack2.pop(); } return str }

利用堆栈判断回文

思路: step1:将字符串顺序遍历压进堆栈 step2:将堆栈依次压出

代码:

function isPalindrome(str){ var stack = new Stack(); var newStr = ''; for (var i = 0; i < str1.length; i++){ stack.push(str1[i]); } var length = stack.top; for (var i = 0; i < length; i++){ newStr += stack.pop(); } return newStr === str; }
转载请注明原文地址: https://www.6miu.com/read-41088.html

最新回复(0)