数据结构关联列表-如何创建头键值对

data structure association list - how to create head key value pairs?

本文关键字:创建 键值对 何创建 关联 列表 数据结构      更新时间:2023-09-26

我有一个关于数据结构关联列表/只添加到头部的单链列表的问题。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);