数据结构与算法javascript描述-栈

198 阅读1分钟

图解栈结构

LIFO

栈结构概念

常见的使用栈的场景

栈函数

递归

常见的栈操作

栈操作

栈操作

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

JS实现一个栈结构

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)

实例演示

进制转换

进制转换

进制转换思路

进制转换思路


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:图片资源来源于网络

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

全栈小窝