数据结构关联列表-如何创建头键值对
data structure association list - how to create head key value pairs?
我有一个关于数据结构关联列表/只添加到头部的单链列表的问题。set函数假设设置(多个)键值对,而get函数应该得到这些对——我不知道如何制作头(一开始假设为null)作为一个对象,由于新创建的节点变成了"新"头-我不明白如何用它的键值对"移动"旧"头。。乐于助人!非常感谢。
这是我的代码(不多,但根本不知道如何从这里开始)
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();
在键值对象中,您应该始终有一个键,因此使用KISS原则:
var object = {};
object['aKey'] = 'some value';
object['otherKey] = 'other value';
如果您想要存储对象,请使用数组:
var myArray = [];
myArrray.push({'key': 'value'});
myArrray.push({'key': 'value'});
myArrray.push({'key1': 'value1'});
如果你想要一个键有很多值:
var object = {};
if(!object.hasOwnProperty('aKey')){
object['aKey'] = [];
}
object['aKey'].push('value');
Javascript很简单,所以保持简单:)
你差不多到了。您在调用新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);
相关文章:
- 正在数组中存储键值对
- 如何将新的键/值对元素添加到现有数组
- 在键值对中对求和值进行下划线
- 返回由键/值对定义的数组
- 在url参数javascript中存储键值对列表
- 将数组转换为键值对
- jQueryAJAX-将额外的键/值对推送到序列化的$_POST数组中
- 使用jQuery从ajax调用访问键值对
- 将动态键值对传递给函数
- d3使用键值对对对多个值的数据进行分组
- 在动态 JavaScript 对象(键/值对)中创建动态数组
- 在JavaScript中创建键/值对列表
- Jquery-从动态表单提交中创建键值对
- 创建dictionary,将数组作为键值对中的值:javaScript
- 如何在JavaScript中为键/值对创建动态键?
- 使用jQuery从过滤器菜单创建键/值对
- 如何在JavaScript中创建键/值对列表
- 数据结构关联列表-如何创建头键值对
- 用于从两个对象属性创建键值对的函数
- 为对象创建键:值对,同时循环并为每个对象设置变量