链接列表数据结构与Javascript [英] Linked List Data Structure with Javascript

查看:53
本文介绍了链接列表数据结构与Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JavaScript找出链表数据结构.但是有一部分我无法理解.

I'm trying to figure out the linked list data structure using Javascript. But there is a part that I'm not able to understand.

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 如何失去对节点的引用.

I don't understand how the variable current loses its reference to the node when you run the removeAt method.

推荐答案

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

If you want to create the link list you can use the below algorithm:-

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++;
}

这篇关于链接列表数据结构与Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆