您可以尝试像这样动态创建链表。
var Linkedlist = function() {
this.head = null;
this.tail = null;
};
function createNode( val ) {
var node = {};
node[ "key" ] = val;
node[ "prev" ] = null;
node[ "next" ] = null;
return node;
}
Linkedlist.prototype.insert = function( val ) {
if ( this.head === null ) {
this.head = createNode( val );
this.tail = createNode( val );
} else {
var newNode = createNode( val );
newNode[ "next" ] = this.head;
newNode[ "prev" ] = null;
this.head[ "prev" ] = newNode;
this.head = newNode;
}
console.log(this);
};
Linkedlist.prototype.search = function( val ) {
var node = this.head;
while ( node[ "key"] != val ) {
node = node[ "next" ];
if ( node === null ) {
break;
}
}
return node;
};
Linkedlist.prototype.remove = function( val ) {
var node = this.search(val);
if ( node != null ) {
if ( node[ "next" ] === null && node[ "prev" ] === null ) {
this.head = null;
this.tail = null;
} else {
if ( node[ "key"] === this.head[ "key" ] ) {
this.head = node[ "next" ];
this.head[ "prev" ] = null;
} else if ( node[ "key"] === this.tail[ "key" ]) {
this.tail = node[ "prev" ];
this.tail[ "next" ] = null;
} else {
node[ "prev" ][ "next" ] = node[ "next" ];
node[ "next" ][ "prev" ] = node[ "prev" ];
}
}
console.log( this );
} else {
console.log("key doesnt exist");
}
};
Linkedlist.prototype.largest = function() {
var node = this.head;
var largest = this.head;
while ( node[ "next"] !== null ) {
if ( node[ "key"] > largest[ "key" ] ) {
largest = node;
}
node = node[ "next" ];
}
return largest;
};
可以如下所示进行实例化。
linkedlist = new Linkedlist();
linkedlist.insert(1);
linkedlist.insert(2);
linkedlist.insert(3);
linkedlist.insert(4);
linkedlist.remove(2);
linkedlist.largest();