javascript LinkedList js 双向循环链表

javascript LinkedList:

function Node(elem, prev, next) {
    this.elem = elem;
    this.prev = prev ? prev : null;
    this.next = next ? prev : null;
}

function LinkedList() {
    this.length = 0;
    this.head = null;
}

LinkedList.prototype.push = function(elem) {
	var newNode = new Node(elem);

    if (this.length === 0) {
        this.head = newNode;
        this.head.prev = newNode;
        this.head.next = newNode;
    } else {
        newNode.next = this.head;
        newNode.prev = this.head.prev;
        this.head.prev.next = newNode;  // !!! CAUTION !!!
        this.head.prev = newNode;        
    }
    ++this.length;
    return this;
}

LinkedList.prototype.shift = function() {	
    if (this.length === 0) {
    	return null;
    }
    var node = new Node(this.head.elem), oHead = this.head;
    this.head.next.prev = this.head.prev;
    this.head.prev.next = this.head.next;
    this.head = this.head.next;
    delete(oHead);
    --this.length;

    return node.elem;
}

LinkedList.prototype.get = function(index) {
	if (index < 0 || index >= this.length) {
		throw new DOMException("LinkedList index out of bounds!");
	}
	var p = this.head;
	for (var i = 0; i < index; i++) {
		p = p.next;
	}
	return p.elem;
}

LinkedList.prototype.forEach = function(callback) {
    var p = this.head;
    do {
        callback(p.elem);
        p = p.next;
    } while (p != this.head);
    return this;
}

LinkedList.prototype.map = function(callback) {
	var newList = new this.__proto__.constructor();
	this.forEach(function(elem) {
		newList.push(callback(elem));
	});
	return newList;
}

LinkedList.prototype.join = function(sep) {
	var s= "";
	if (this.length === 0 || this.length === 1) {
		return s;
	}
	var p = this.head;
    do {
        s += p.elem.toString() + sep;
        p = p.next;
    } while (p != this.head.prev);
    s += p.elem.toString();
	return s;
}

LinkedList.prototype.toString = function() {
	return this.join(',');
}

  

  

// Array like

//test

var list = new LinkedList();

for (var i = 1; i <10; i++) {
	list.push(i);	
}
// list.forEach(function(elem) {console.log(elem);});
var newList = list.map(function(elem) {
	return elem - 1;
});
console.log(newList.toString());
newList.shift();
console.log(newList.toString());

 0,1,2,3,4,5,6,7,8

1,2,3,4,5,6,7,8

猜你喜欢

转载自www.cnblogs.com/mingzhanghui/p/9317179.html