查看: 90|回复: 0

JavaScript 算法 1_1 下压堆栈 (链表实现)

[复制链接]

2

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2011-8-16
发表于 2021-1-14 13:26:00 | 显示全部楼层 |阅读模式

JavaScript 算法 1_1 下压堆栈 (链表实现)

链表是一种递归的数据结构

目录
  • JavaScript 算法 1_1 下压堆栈 (链表实现)
    • 1. 节点结构
    • 2. 构造链表
    • 3. 从表头插入和删除元素
    • 4. 代码实现


1. 节点结构

node = {
	ele: null,
    next: null,
}

这里使用了 ele 作为一个节点的元素内容, next 作为下个节点的索引


2. 构造链表

let next = {};
Object.assign(next, {ele:null, next:null});
next.ele = item;

使用了 Object.assign 函数复制了节点结构


3. 从表头插入和删除元素

 push(item){
    let oldFirst = this.first;
    let next = {};
    Object.assign(next, {ele: null, next: null});
    next.ele = item;
    this.first = next;
    this.first.next = oldFirst;
    this.count++;
  }
  pop(){
    let top = this.first.ele;
    this.first = this.first.next;
    this.count--;
    return top;
  }
  • 插入时先保存栈顶元素到 oldFirst, 后创建 next 节点, 置为栈顶
  • 删除时移除栈顶元素并返回

4. 代码实现

链表类

// 类定义
class Stack{
  constructor() {
    // 栈顶元素, 包括 next 和 ele
    this.first = null;
    this.count = 0;
  }
  isEmpty(){
    return this.count === 0;
  }
  size(){
    return this.count;
  }
  push(item){
    let oldFirst = this.first;
    let next = {};
    Object.assign(next, {ele: null, next: null});
    next.ele = item;
    this.first = next;
    this.first.next = oldFirst;
    this.count++;
  }
  pop(){
    let top = this.first.ele;
    this.first = this.first.next;
    this.count--;
    return top;
  }
  // 下回分解迭代器
  // [Symbol.iterator](){
  //
  // }
}

使用方式

const stack = new Stack();

// 可以使用任意类型放入
stack.push(20);
stack.push('小歪');
stack.push([20, 30]);
stack.push({name: '张三'});

let pop = stack.pop();
// pop: { name: '张三' } 
pop = stack.pop();
// [ 20, 30 ]
pop = stack.pop();
// 小歪
pop = stack.pop();
// 20
console.log(stack);
// Stack { first: null, count: 0 }

代码可以按要求运行 √

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部