js-实现单向链表

论坛 期权论坛 脚本     
已经匿名di用户   2022-7-2 21:59   2295   0
单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始。
javascript实现单向链表代码如下:
function LinkedList() {
 var Node = function (element) { //表示要加入列表的项,next属性指向下一个节点项的指针
  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;
   while (current.next) {//while循环寻找最后元素
    current = current.next;
   }
   current.next = node;
  }
  length++;//更新列表的长度
 };
 this.insert = function (position, element) {//在任意一个位置插入一个元素,position为位置,element为元素
  //检查越界值
  if (position >= 0 && position <= length) {
   var node = new Node(element),
    current = head,
    previous,
    index = 0;
   if (position === 0) {//在第一个位置添加
    node.next = current;
    head = node;
   } else {
    while (index++ < position) {
     previous = current;
     current = current.next;
    }
    node.next = current;
    previous.next = node;
   }
   length++;
   return true;
  }
  else {
   return false;
  }
 };
 this.removeAt = function (position) {//移除指定位置的元素
  if (position > -1 && position < length) {
   var current = head,
    previous,
    index = 0;
   if (position === 0) {
    head = current.next;
   } else {
    while (index++ < position) {
     previous = current;
     current = current.next;
    }
    length--;
    return current.element;
   }

  } else {
   return null;
  }
 };
 this.remove = function (element) {//移除某元素
  var index = this.indexOf(element);
  return this.removeAt(index);
 };
 this.indexOf = function (element) {//是否包含某元素,返回所在位置
  var current = head,
   index = -1;
  while (current) {
   index++;
   if (element === current.element) {
    return index;
   }
   current = current.next;
  }
  return -1;
 };
 this.isEmpty = function () {//检查链表是否为空
  return length === 0;
 };
 this.size = function () {//返回链表的长度
  return length;
 };
 this.toString = function () {//输出链表中的值
  var current = head,
   string = '';
  while (current) {
   string += current.element + " ";
   current = current.next;
  }
  return string;
 };
 this.getHead = function () {//获得head
  return head;
 };
}
var list = new LinkedList();
list.append(15);
list.append(8);
list.append(12);
list.append(10);
list.append(6);
console.log("链表是否为空?" + list.isEmpty());
console.log("链表长度:" + list.size());
console.log(list.toString());
console.log(list.indexOf(10));


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP