【问题标题】:Linked List Data Structure with Javascript带有 Javascript 的链表数据结构
【发布时间】:2023-03-23 23:55:01
【问题描述】:

我正在尝试使用 Javascript 找出链表数据结构。但是有一部分看不懂。

function LinkedList() {
  var Node = function(element) {
    this.element = element;
    this.next = null;
  }

  var length = 0;
  var head = null;

  this.append = function(element) {
    var node = new Node(element),
      current;

    if (head === null) {
      head = node;
    } else {
      current = head;

      //loop the list until find last item
      while (current.next) {
        current = current.next
      }

      //get last item and assign next to node to make the link
      current.next = node
    }
    length++;
  }

  this.removeAt = function(position) {
    //check for out of bounds values
    if (position > -1 && position < length) {
      var current = head,
        previous,
        index = 0;

      if (position === 0) {
        head = current.next;
      } else {
        while (index++ < position) {
          debugger;
          previous = current;
          current = current.next;
        }

        previous.next = current.next;
      }

      length--;

      return current.element;

    } else {
      return null;
    }
  }

  this.toString = function() {
    var current = head,
      string = '';

    while (current) {
      string = current.element;
      current = current.next;
    }

    return string;
  }
}

var list = new LinkedList();
list.append(15);
list.append(10);
list.append(11);
list.removeAt(1);

我不明白当您运行 removeAt 方法时,变量 current 是如何失去对节点的引用的。

【问题讨论】:

  • 请用一些空格格式化您的代码 - 没有格式化就很难解析,并且不太可能获得帮助。
  • 当您说“... current 失去对节点的引用...”时,您是在问如何/为什么删除节点?
  • current 是您的 removeAt 方法的局部变量,那么您看到的问题到底是什么?我检查了您的代码,似乎一切正常,除了 toString 方法可能只返回尾节点的内容。您能否添加代码来演示您看到的问题?产生了你意想不到或不想要的结果?
  • @nurdyguy 是的,那是我没有得到的部分
  • @marquezgon 当您使用previous 节点并使用previous.next = current.next 将他的next 设置为current.next 时,结果是previous 现在直接链接到节点之后current。因此,您已从列表中删除 current。然后在函数结束时,current 变量超出范围并被有效删除。

标签: javascript data-structures linked-list


【解决方案1】:

如果要创建链接列表,可以使用以下算法:-

var linkedList = function(){
  this.head=null;
  this.tail=null;
  this.size=0;
}
linkedList.prototype.add=function(obj){
 if(!this.head){
   this.head=obj;
   this.tail=obj;
   this.size++;
   return
 }
 this.tail.next = obj;
 this.tail=obj;
 this.size++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多