生成链表结构

js对象模拟链表结构

console.log(fn([1, 2, 3, 4])); // 输出在下面
function fn(arr) {
  var head = { val: 1, next: null };
  var node = head;
  for (var i = 0; i < arr.length; i++) {
    var obj = {};
    obj.val = arr[i];
    obj.next = null;
    node = node.next = obj;
  }
  return head.next;
}

输出内容为:

{
    "val": 1,
    "next": {
        "val": 2,
        "next": {
            "val": 3,
            "next": {
                "val": 4,
                "next": null
            }
        }
    }
}

构造函数模拟对象结构

console.log(fn[(1, 2, 3, 4)]);
function fn(arr) {
  var head = new ListNode();
  var node = head;
  for (var val of arr) {
    node = node.next = new ListNode(val);
  }
  return head.next;
  function ListNode(val, next) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
  }
}

你可能感兴趣的:(链表,数据结构)