当前位置:Gxlcms > JavaScript > 利用JavaScript实现栈的数据结构示例代码

利用JavaScript实现栈的数据结构示例代码

时间:2021-07-01 10:21:17 帮助过:5人阅读

前言

本文主要给大家介绍的是关于JavaScript实现栈的数据结构的相关内容,分享出来供大家参考学习,话不多少,来一起看看详细的介绍:

堆栈(英语:stack),也可直接称栈,在计算机科学中,是一种特殊的串列形式的数据结构,它的特殊之处在于只能允许在链接串列或阵列的一端(称为堆叠顶端指标,英语:top)进行加入数据(push)和输出数据(pop)的运算。另外栈也可以用一维数组或连结串列的形式来完成。 

由于堆叠数据结构只允许在一端进行操作,因而按照后进先出(LIFO, Last In First Out)的原理运作。 – 维基百科

上面是维基百科对栈的解读。下面我们用JavaScript(ES6)代码对栈的数据结构进行实现

实现一个Stack类

  1. /**
  2. * Stack 类
  3. */
  4. class Stack {
  5. constructor() {
  6. this.data = []; // 对数据初始化
  7. this.top = 0; // 初始化栈顶位置
  8. }
  9. // 入栈方法
  10. push() {
  11. const args = [...arguments];
  12. args.forEach(arg => this.data[this.top++] = arg);
  13. return this.top;
  14. }
  15. // 出栈方法
  16. pop() {
  17. if (this.top === 0) throw new Error('The stack is already empty!');
  18. const peek = this.data[--this.top];
  19. this.data = this.data.slice(0, -1);
  20. return peek;
  21. }
  22. // 返回栈顶元素
  23. peek() {
  24. return this.data[this.top - 1];
  25. }
  26. // 返回栈内元素个数
  27. length() {
  28. return this.top;
  29. }
  30. // 清除栈内所有元素
  31. clear() {
  32. this.top = 0;
  33. return this.data = [];
  34. }
  35. // 判断栈是否为空
  36. isEmpty() {
  37. return this.top === 0;
  38. }
  39. }
  40. // 实例化
  41. const stack = new Stack();
  42. stack.push(1);
  43. stack.push(2, 3);
  44. console.log(stack.data); // [1, 2, 3]
  45. console.log(stack.peek()); // 3
  46. console.log(stack.pop()); // 3, now data is [1, 2]
  47. stack.push(3);
  48. console.log(stack.length()); // 3
  49. stack.clear(); // now data is []

用栈的思想将数字转换为二进制和八进制

  1. /**
  2. * 将数字转换为二进制和八进制
  3. */
  4. const numConvert = (num, base) => {
  5. const stack = new Stack();
  6. let converted = '';
  7. while(num > 0) {
  8. stack.push(num % base);
  9. num = Math.floor(num / base);
  10. }
  11. while(stack.length() > 0) {
  12. converted += stack.pop();
  13. }
  14. return +converted;
  15. }
  16. console.log(numConvert(10, 2)); // 1010

用栈的思想判断给定字符串或者数字是否是回文

  1. /**
  2. * 判断给定字符串或者数字是否是回文
  3. */
  4. const isPalindrome = words => {
  5. const stack = new Stack();
  6. let wordsCopy = '';
  7. words = words.toString();
  8. Array.prototype.forEach.call(words, word => stack.push(word));
  9. while(stack.length() > 0) {
  10. wordsCopy += stack.pop();
  11. }
  12. return words === wordsCopy;
  13. }
  14. console.log(isPalindrome('1a121a1')); // true
  15. console.log(isPalindrome(2121)); // false

上面就是用JavaScript对栈的数据结构的实现,有些算法可能欠妥,但是仅仅是为了演示JS对栈的实现😄

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

人气教程排行