我在做链接列表数据结构。原型包括一个方法,从列表中弹出(删除)最后一项,我试图通过查找最后一个对象来完成,然后将其设置为null
。它似乎没有工作。工作是将前一个对象中的引用('指针')设置为null
。我仍然是一个相对JS OOP新手,不能让我的大脑理解为什么。代码:Javascript:链接列表:无法删除对象引用
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
希望有一些见解,以及任何其他改进功能的提示。谢谢!
啊,总觉得!是的,这是一个数据结构和算法的编程练习,只是为了好玩而尝试。谢谢! – pete
从列表的前面“push”和“pop”实际上会更快。为您节省了遍历它的需求。只需保存对'rootNode'的引用,将'rootNode'引用设置为'nextNode',将原始节点的'nextNode'引用设置为null并将其返回。推送相同。你需要遍历列表的唯一原因是如果你想强制执行队列而不是堆栈行为。 – citizenslave