【发布时间】:2014-03-15 08:02:46
【问题描述】:
我正在做一个链表数据结构。原型包括一个方法来弹出(删除)列表中的最后一项,我试图通过查找最后一个对象来完成,然后将其设置为null。它似乎不起作用。起作用的是将前一个对象中的引用(“指针”)设置为null。我仍然是一个相对的 JS OOP 新手,无法让我的大脑理解为什么。代码:
function LinkedList() {
this._rootNode = null;
this._length = 0;
}
LinkedList.prototype = {
push: function(data) {
var newNode = {
data: data,
nextNode: null
};
// initialize this._rootNode or subsequent .nextNode with newNode
this._length++;
},
pop: function() {
var selectedNode, perviousNode;
if ( this._rootNode ) {
if ( this._length > 1 ) {
selectedNode = this._rootNode;
while ( selectedNode.nextNode ) {
previousNode = selectedNode; // <-- shouldn't need this?
selectedNode = selectedNode.nextNode;
}
selectedNode = null; // <-- doesn't delete it
// previousNode.nextNode = null; // <-- works (but feels unnecessary?)
} else {
this._rootNode = null;
}
this._length--;
}
},
// more methods..
};
/* --- Main Prorgam --- */
var list = new LinkedList();
list.push('AAA');
list.push('BBB');
list.pop();
console.log(list._rootNode.nextNode.data); <-- 'BBB' still there
希望能提供一些见解,以及有关改进功能的任何其他提示。谢谢!
【问题讨论】:
标签: javascript oop linked-list