一、数据结构(栈)

1、栈常见有哪些操作

push(element):添加一个新元素到栈顶位置

pop():移除栈顶元素,同时返回被移除的元素

peek():返回栈顶的元素,不对栈做任何的修改(这个方法不会移除站的元素,仅仅返回它)

isEmpty():如果栈里没有任何元素就返回true,否则返回false

size():返回栈里面的元素个数。这个方法和数组的length属性很类似

toString():将栈结构的内容以字符形式返回

2、栈结构的封装

// 栈结构的封装
export default class Stack {

  constructor() {
    this.items = [];
  }
  // push(item) 压栈操作,往栈里面添加元素
  push(item) {
    this.items.push(item);
  }
  // pop() 出栈操作,从栈中取出元素,并返回取出的那个元素
  pop() {
    if(this.isEmpty()) throw new Error('栈空了');
    return this.items.pop();
  }
  // peek() 查看栈顶元素
  peek() {
    if(this.isEmpty()) throw new Error('栈空了');
    return this.items[this.items.length - 1];
  }
  // isEmpty() 判断栈是否为空
  isEmpty() {
    return this.items.length === 0;
  }
  // size() 获取栈中元素个数
  size() {
    return this.items.length;
  }

  // toString() 返回以字符串形式的栈内元素数据
  toString() {
    let result = '';
    for (let item of this.items) {
      result += item + ' ';
    }
    return result;
  }
}

测试

import Stack from './stack'
const  stack=new Stack()
stack.push('a')
stack.push('b')
stack.push('c')
stack.push('d')
console.log(stack.items)
stack.pop()
console.log(stack.items)
console.log(stack.peek())
console.log(stack.size())
console.log(stack.toString())
console.log(stack.isEmpty())

测试结果

3、应用(十进制转二进制)

//引入栈结构的封装
import Stack from "./stack";
//封装十进制转化为二进制
export default function dec2bin(num){
    //1、创建stack
const stack=new Stack()
//2、循环取余数
while (num) {
    let remainder=num%2
    num=Math.floor(num/2);
    stack.push(remainder)
}
let binString=''
while(!stack.isEmpty()){
binString+=stack.pop()
}

return binString

}

测试

import dec2bin from './dec2bin'
const Dec2bin=dec2bin(100)
console.log(Dec2bin)
console.log(dec2bin(10))
console.log(dec2bin(50))

结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值