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

标签 javascript data-structures singly-linked-list

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

相关文章:

javascript - Angularjs ngRoute 不工作

javascript - 在微型 mce 插件上显示日期时间选择器

c - 如何对这些结构进行编程?

algorithm - 在哪里可以找到图形测试套件?

java - 如何在Java中不使用构造函数手动实现链表?

javascript - 选择后回到默认语句?

javascript - Angular:如何检测当前组件中的路由变化?

java - 如何解决错误 : 15: error: cannot infer type arguments for PriorityQueue<> in openjdk 1. 7.0_95?

c - 错误: incompatible type for argument 1 of 'push'

c++ - 如何将元素添加到链表的末尾