node 链表
发布于 7 年前 作者 yulipu 4294 次浏览 来自 分享

我只是想说 js 还有 iterator 这个东西 挺好用

var list = new LinkedList();
list.add(123);
list.add({a:1});
list.add('abc');

for(var data of list) {
	console.log(data);
}


class LinkedList {
    
    /**
     * constructor
     */
    constructor() {
        this.headNode = null;
        this.tailNode = null;
        this.size = 0;
        
        this.headNode = this.tailNode = new LinkedList.Node(null, null);
    }
    
    [Symbol.iterator]() {
        return this;
    }
    
    next() {
        if(undefined === this.currentIteratorNode) {
            this.currentIteratorNode = this.headNode.next;
            
        } else {
            this.currentIteratorNode = this.currentIteratorNode.next;
        }
        
        return null === this.currentIteratorNode ? {done: true} :
            {done: false, value: this.currentIteratorNode.data};
    }
    
    add(data) {
        var node = new LinkedList.Node(data, null);
        // 队尾指向新节点
        this.tailNode.next = node;
        // 重新指定尾节点
        this.tailNode = node;
        // 计数
        this.size++;
    }
    
    take() {
        // 为空直接返回
        if(this.headNode === this.tailNode) {
            return null;
        }
        
        // 队列中头节点
        var tmpHeadNode = this.headNode.next;
        var data = tmpHeadNode.data;
        
        // 从队列去除头节点
        this.headNode.next = tmpHeadNode.next;
        tmpHeadNode.next = null;
        tmpHeadNode = null;
        
        // 没节点了 重置 tail
        if(null === this.headNode.next) {
            this.tailNode = this.headNode;
        }
        
        this.size--;
        
        return data;
    }
    
    clear() {
        while(0 !== this.size) {
            this.take();
        }
    }
    
    /**
     * toString
     */
    toString() {
        var str = '[ ';
        
        /*
        for(let current = this.headNode.next; null !== current; current = current.next) {
            str += current.data + ' ';
        }
        */
        for(let data of this) {
            str = str + data + ' ';
        }
        
        return str + ' ]';
    }
    
}
LinkedList.Node = class {
    
    /**
     * constructor
     */
    constructor(data, next) {
        this.data = data;
        this.next = next;
    }
    
};
7 回复
  [Symbol.iterator]() {

这是什么?

@yakczh 这个是修改遍历器行为的,存在这个属性让他可遍历

楼上说的对 就是想强调一下有这么个特性

其实有原生的linkList模块

const linkList = require('_linklist')

加_看起来是这个linkList仅仅给内部的timer定时器模块使用了,而且没有提供插入和查询的公共函数(对于timer来说只有遍历、删除和挂到尾部的操作) 以前写过一些解析:https://cnodejs.org/topic/5800c054487e1e4578afb516

回到顶部