结构pop_快速入门数据结构:栈

c352506a542b9856347c5ea6cade1e52.png

图解栈结构

fd2f17068d67d84e6ec2890689fede05.png

fc0717caf2dc19b1fd2455c40bf29a49.png

常见的使用栈的场景

df453f36049f116afc2b067a3ad68d08.png

70f0b3d24d40404388b8616d67268c94.png

常见的栈操作

5560a7bab4349b76da72db493de25e07.png

c953f5449b34f5f31d6410eab89fc262.png

JS通过数组实现一个栈结构

7d4a4cb116ea1bdeea78788854d72567.png
const assert = require('assert')

class Stack {
  constructor() {
    this.items = []
  }
  push(item) {
    return this.items.push(item)
  }
  pop() {
    return this.items.pop()
  }
  peek() {
    return this.items[this.size() - 1]
  }
  size() {
    return this.items.length
  }
  isEmpty() {
    return this.size() === 0
  }
  clear() {
    this.items = []
  }
}


// test case

const s = new Stack()
s.push(1)
s.push(2)
assert.strictEqual(s.size(), 2)
s.pop()
assert.strictEqual(s.size(), 1)
s.push(3)
assert.strictEqual(s.peek(), 3)
s.clear()
assert.strictEqual(s.size(), 0)

实例演示

进制转换

ae18710898a6637267d6fa98c1e657fd.png

66132122e64fff4308440809dfd3510f.png

97970ff3c1e7a7496d0b3eba45d9cba0.png
const assert = require('assert');

class Stack {
  constructor() {
    this.items = []
  }
  push(item) {
    return this.items.push(item)
  }
  pop() {
    return this.items.pop()
  }
  peek() {
    return this.items[this.size() - 1]
  }
  size() {
    return this.items.length
  }
  isEmpty() {
    return this.size() === 0
  }
  clear() {
    this.items = []
  }
}

function hexConverse(s1, base) {
  let result = ''
  const s = new Stack()
  while (s1) {
    s.push(s1 % base)
    s1 = Math.floor(s1 / base)
  }
  while (s.size()) {
    result += s.pop()
  }
  return result
}

assert.strictEqual(hexConverse(10, 2), '1010')

PS:图片资源来源于网络

有兴趣的请关注我的公众号

434fd772092bb7b74aa4567b4d1a9d4d.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值