我有一个关于数据结构关联列表/单链表的问题,它只添加到头部。 set 函数应该设置(多个)键值对,而 get 函数应该获取这些对 - 我不明白如何制作头部(一开始应该为空) 成为一个对象,并且由于新创建的节点成为"new"头 - 我不明白如何用它的键值对“移动”“旧”头。 很高兴有任何帮助!谢谢!
这是我的代码(不多,但根本不知道如何从这里开始)
function List () {
this.head=null;
}
function ListN (key, value, next) {
this.key = key;
this.value = value;
this.next = next;
}
Alist.prototype.set = function (key, value) {
// this.key=value;
var newNode=new ListN(key, value);
this.head=newNode;
};
Alist.prototype.get = function (key) {
return this.key;
};
smallList = new List();
最佳答案
你就快到了。您在调用 new ListN 时错过了前一个节点。
var newNode = new ListN(key, value, this.head);
// ^^^^^^^^^
function List() {
this.head = null;
}
List.prototype.set = function (key, value) {
function ListN(key, value, next) {
this.key = key;
this.value = value;
this.next = next;
}
var node = this.head;
while (node) {
if (node.key === key) {
node.value = value;
return;
}
node = node.next;
}
this.head = new ListN(key, value, this.head);
};
List.prototype.get = function (key) {
var node = this.head;
while (node) {
if (node.key === key) {
return node.value;
}
node = node.next;
}
};
var smallList = new List();
smallList.set('one', 'abc');
console.log(smallList);
smallList.set('two', 'def');
console.log(smallList);
console.log(smallList.get('one'));
console.log(smallList.get('two'));
console.log(smallList.get('three'));
smallList.set('two', 'xyz');
console.log(smallList);
关于javascript - 数据结构关联列表-如何创建头键值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38463229/