数据结构 - 链表

本文介绍了一种使用ES5语法实现链表数据结构的方法,包括链表的创建、元素的追加、插入、删除及查找等操作,是理解链表原理和实践链表编程的良好示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链表

数据结构 - 链表。

// 链表实现
// ES5
var linkedList = function() {
  // 链表头
  var head = null;
  // 链表长度
  var length = 0;

  // 辅助类:节点
  var Node = function(element) {
    this.element = element;
    this.next = null;
  };

  // 链表尾追加元素
  this.append = function(element) {
    var node = new Node(element);

    if (head == null) {
      head = node;
    } else {
      var current = head;
      while (current.next) {
        current = current.next;
      }
      // while循环执行完后,current已经是链表的最后一项了
      current.next = node;
    }
    length++;
  };

  // 链表某个位置添加元素
  this.insert = function(position, element) {
    // 越界
    if (position > -1 && position < length) {
      var node = new Node(element);
      var current = head;
      // 在链表头添加
      if (position == 0) {
        head = node;
        head.next = current;
      // 在其他位置添加
      } else {
        var index = 0;
        var previous = null;
        while (index < position) {
          previous = current;
          current = current.next;
          index++;
        }
        previous.next = node;
        node.next = current;
      }
      length++;
    }
  };

  // 链表某个位置移除元素
  this.removeAt = function(position) {
    // 越界
    if (position > -1 && position < length) {
      var current = head;
      if (position == 0) {
        head = current.next;
      } else {
        var index = 0;
        var previous = null;
        while(index < position) {
          previous = current;
          current = current.next;
          index++;
        }
        // while循环执行完后,index == position
        previous.next = current.next;
      }
      length--;
      return current;
    }
    return null;
  };

  // 获取元素在链表中的位置
  this.indexOf = function(element) {
    var index = 0;
    var current = head;
    while (current) {
      if (current.element == element) {
        return index;
      }
      current = current.next;
      index++;
    }
    return -1;
  };

  // removeAt(position) 删除某个位置的元素
  // indexOf(element)   获取某个元素的位置
  this.remove = function(element) {
    return this.removeAt(this.indexOf(element));
  };

  // 检查链表是否为空
  this.isEmpty = function() {
    return length == 0;
  };

  // 获取链表长度
  this.size = function() {
    return length;
  };

  // 检查链表头
  this.getHead = function() {
    return head;
  };
};

var l = new linkedList();
l.append(1);
l.append(2);
l.append(3);

l.insert(1, 10);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值