实现栈结构

//创建栈
function Stack (){
let items = [] this.push = function(element){
items.push(element)
}
this.pop = function(){
return items.pop()
}
this.peek = function(){
return items[items.length - 1]
}
this.isEmpty = function(){
return items.length === 0
}
this.size = function(){
return items.length
}
this.clear = function(){
items = []
}
this.print = function(){
console.log(items.toString())
}
}

ES6改造

//使用Symbol添加私有属性
class Stack {
let _items = Symbol()
constructor(){
this[_items] = []
}
push(element){
this[_items].push(element)
}
} //可以拿到所有的symbol对象
Object.getOwnPropertySymbols(Stack) //使用weakMap
const items = new weakMap() class Stack {
constructor(){
items.set(this,[])
}
push(element){
let s = items.get(this)
s.push(element)
}
pop(){
let s = items.get(this)
let r = s.pop()
return r
}
} //利用闭包实现私有属性
let Stack = (function(){
const items = new WeackMap() class Stack {
constructor(){
items.set(this,[])
}
push(element){
let s = items.get(this)
s.push(element)
}
pop(){
let s = items.get(this)
let r = s.pop()
return r
}
}
return Stack
})()

进制转换

//10进制转2进制
function divideBy2(decNumber){
var remStack = new Stack(),
rem,
binaryString = ''; while(decNumber > 0){
rem = Math.floor(decNumber % 2)
remStack.push(rem)
decNumber = Math.floor(decNumber / 2)
} while(!remStack.isEmpty()){
binaryString += remStack.pop().toString()
}
} //任意进制转换
function baseConverter(decNumber,base){
const remStack = new Stack();
const digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let number = decNumber;
let rem;
let baseString = ''; if (!(base >= 2 && base <= 36)) {
return '';
} while (number > 0) {
rem = Math.floor(number % base);
remStack.push(rem);
number = Math.floor(number / base);
} while (!remStack.isEmpty()) {
baseString += digits[remStack.pop()];
} return baseString;
}

平衡圆括号

function balancedSymbols(symbols){
const stack = new Stack()
const opens = `([{`
const closers = `)]}` let balanced = true
let index = 0
let symbol
let top while(index < symbols.length && balanced){
symbol = symbols[index] if(opens.indexOf(symbol) >= 0){
stack.push(symbol)
} else if(stack.isEmpty()){
balanced = false
} else {
top = stack.pop()
if(!(opens.indexOf(top) === closers.indexOf(symbol))){
balanced = false
}
} index ++
}
return balanced && stack.isEmpty()
}

汉诺塔

递归,即定义一组基本操作,这组操作将规模小一点(或大一点)的操作当做一个整体——无需关心它的细节,只当它已经完成了——然后执行剩下的操作。而在更小或更大的规模中也依此操作,直到规模达到预定值。

function towerOfHanoi(plates,source,helper,dest,sourceName,helperName,destName,moves = []){
if(plates <= 0){
return moves
}
if(plates === 1){
dest.push(source.pop())
const move = {}
move[sourceName] = source.toString()
move[helperName] = helper.toString()
move[destName] = dest.toString()
moves.push(move)
}
else {
towerOfHanoi(
plates - 1,
source,
dest,
helper,
sourceName,
destName,
helperName,
moves
)
dest.push(source.pop())
const move = {}
move[sourceName] = source.toString()
move[helperName] = helper.toString()
move[destName] = dest.toString()
moves.push(move)
towerOfHanoi(
plates - 1,
helper,
source,
dest,
helperName,
sourceName,
destName,
moves
)
}
return moves
} function hanoiStack(plates){
const source = new Stack()
const dest = new Stack()
const helper = new Stack() for(let i = plates; i > 0; i --){
source.push(i)
} return towerOfHanoi(
plates,
source,
helper,
dest,
source,
helper,
dest
)
} function hanoi(plates,source,helper,dest,moves = []){
if(plates <= 0){
return moves
}
if(plates === 1){
moves.push([source,dest])
} else {
hanoi(
plates - 1,
source,
dest,
helper,
moves
)
moves.push([source,dest])
}
return moves
}
//用栈来实现汉诺塔
console.log(hanoiStack(3));
//用递归来来实现
console.log(hanoi(3, 'source', 'helper', 'dest'));

js实现栈结构的更多相关文章

  1. 原生JS实现栈结构

    1. 前言 栈,是一种遵从后进先出(LIFO,Later-In-First-Out)原则的有序集合.新添加的元素都保存在栈的一端,称作栈顶,另一端叫做栈底.在栈中,新元素都靠近栈顶,旧元素都靠近栈底. ...

  2. (js描述的)数据结构[栈结构](2)

    (js描述的)数据结构[栈结构](2) 一.什么是栈结构 1.一种受限制的线性结构,这种结构可以基于数组来实现. 2.可以抽象成一个容器,上面的是栈顶,底下的是栈底.所以仅允许对栈顶进行操作, 二.栈 ...

  3. JS数据结构与算法-栈结构

    一.认识栈结构 栈也是一种非常常见的数据结构,并且在程序中的应用非常广泛 数组 我们知道数组是一种线性结构,并且可以在数组的任意位置插入和删除数据. 但是有时候,我们为了实现某些功能,必须对这种任意性 ...

  4. 数据结构笔记--栈的总结及java数组实现简单栈结构

    杂谈"栈"结构: 栈(Stack)是一种插入删除操作都只能在一个位置上进表,这个位置位于表的末端,叫做栈顶(Top). 对栈的基本操作有push和pop,表示进栈和出栈.也就相当于 ...

  5. Atitit 跨平台异常处理(2)--------异常转换 -----java c# js异常对象结构比较and转换

    Atitit 跨平台异常处理(2)--------异常转换 -----java c# js异常对象结构比较and转换 { "@type":"java.lang.Runti ...

  6. javascript使用栈结构将中缀表达式转换为后缀表达式并计算值

    1.概念 你可能听说过表达式,a+b,a+b*c这些,但是前缀表达式,前缀记法,中缀表达式,波兰式,后缀表达式,后缀记法,逆波兰式这些都是也是表达式. a+b,a+b*c这些看上去比较正常的是中缀表达 ...

  7. javascript中的栈结构

    1.栈的定义 栈是一种和列表类似的数据结构,可以用它来解决很多的编程问题,栈是一种高效的数据结构,因为数据只能在栈的顶端添加或者删除,所以这样的操作很快而且容易实现. 栈是一种特殊的列表,站内的元素只 ...

  8. 用C++类模板实现栈结构出现的问题以及思考

    C++中使用了模板来减少方法相同但是类型不一样带来的函数重载以及大量复制代码的问题.这里主要说说类模板   类模板的定义:   template<TYPENAME Type>   clas ...

  9. 用Java实现栈结构

    栈是一种先进后出的数据结构,出栈入栈都是操作的栈顶元素,下面是利用Java语言实现的一个简单的栈结构 class MyStack{ private int size;//栈大小 private Obj ...

随机推荐

  1. [Objective-C语言教程]错误处理(22)

    在Objective-C编程中,错误处理由Foundation框架中提供的NSError类提供处理. 与仅使用错误代码或错误字符串相比,NSError对象封装了更丰富且更具可扩展性的错误信息. NSE ...

  2. Antd 初识

    mark 参考 antd - 官网:Ant Design Pro: Ant Design - github:Ant Design pro - github:

  3. FFmpeg工具使用总结

    . 一. FFmpeg是什么? 简单说,FFmpeg就是一个很好的,免费的,开源的视频转换工具.详细说,FFmpeg是一个开源免费跨平台的视频和音频流方案,属于自由软件,采用LGPL或GPL许可证(依 ...

  4. python-------打印与字符串格式化

    print python中每次执行print时都会在新的一行上开始.形如:print(’xiao') print('ming') 结果为:>>>xiao >>>mi ...

  5. 【转载】Java 9 新特性——模块化

    来自 <http://www.jianshu.com/p/053a5ca89bbb#> 前言 年,我们将迎来 Java 语言的 22 岁生日,22岁,对于一个人而言,正是开始大展鸿图的年纪 ...

  6. 架构师养成记--24.linux常用命令

    一.Linux 文件 根据上文Linux 文件说明1.文件的rwx    d开头表示文件夹,    -开头的表示文件,    l开头表示链接文件    r:read,w:write,x:execute ...

  7. C#-WebForm-★★★JQuery知识——基础知识、选择器、事件★★★

    JQuery 与 JS 之间的转换 将JQuery转换为JS —— get(0) 例如:alert( $("#d1").get(0).offsetwidth ); 将JS 转换为J ...

  8. string常用字符串操作函数

    1.strdup和strndup 说明:strdup() 函数将参数 s 指向的字符串复制到一个字符串指针上去,这个字符串指针事先可以没被初始化.在复制时,strdup() 会给这个指针分配空间,使用 ...

  9. 网络编程-echo服务器

    代码: #coding="utf-8" #name=echo服务器 from socket import * #1.创建套接字 udpSocket = socket(AF_INET ...

  10. selenium和appium启动的感悟

    阅读源码后整理记录如下: selenium : 1.若为webdriver.Chrome()方式启动:①子程序打开chromedriver.exe程序,程序打开后,监听9515端口作为remote_s ...