JS实现 设计链表

设计链表的实现。单链表中的节点应该具有两个属性:val 和 next。val 是当前节点的值,next 是指向下一个节点的指针/引用。
在链表类中实现这些功能:
get(index):获取链表中第 index 个节点的值。如果索引无效,则返回-1。
addAtHead(val):在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点。
addAtTail(val):将值为 val 的节点追加到链表的最后一个元素。
addAtIndex(index,val):在链表中的第 index 个节点之前添加值为 val 的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点。
deleteAtIndex(index):如果索引 index 有效,则删除链表中的第 index 个节点。

整体实现:

相关代码:

// 初始化数据结构
var MyLinkedList = function () {
    this.head = null
    this.rear = null
    this.len = 0
};

function ListNode(val) {
    this.val = val
    this.next = null
}
// 获取index位置节点的值
MyLinkedList.prototype.get = function (index) {
    if (index < 0 || index > this.len - 1) {
        return -1
    }
    var node = this.head
    while (index-- > 0) {
        if (node.next == null) {
            return -1
        }
        node = node.next
    }
    return node.val
};

// 在链表头部添加节点
MyLinkedList.prototype.addAtHead = function (val) {
    var node = new ListNode(val) //每次添加都创建一个节点
    if (this.head == null) {
        this.rear = node
    } else {
        node.next = this.head
    }
    this.head = node
    this.len++
};

//在链表尾部添加节点
MyLinkedList.prototype.addAtTail = function (val) {
    var node = new ListNode(val)
    if (this.head == null) {
        this.head = node
    } else {
        this.rear.next = node
    }
    this.rear = node
    this.len++
};

// 在指定位置之前插入节点
MyLinkedList.prototype.addAtIndex = function (index, val) {
    if (index <= 0) {
        return this.addAtHead(val)
    }
    if (this.len < index) {
        return 
    }
    if (index == this.len) {
        return this.addAtTail(val)
    }
    var node = this.head
    while (index-- > 1) { //遍历链表
        node = node.next
    }
    var newnode = new ListNode(val)
    newnode.next = node.next
    node.next = newnode
    this.len++
};

// 删除指定位置index的节点
MyLinkedList.prototype.deleteAtIndex = function (index) {
    if (index < 0 || index > this.len - 1 || this.len == 0) {
        return
    }
    if (index == 0) {
        this.head = this.head.next
        this.len--
        return
    }
    var node = this.head
    var myindex = index;
    while (index-- > 1) { //遍历链表
        node = node.next
    }
    if (myindex == (this.len - 1)) {
        this.rear = node
    }
    node.next = node.next.next
    this.len--
};


运行相关代码:

var obj = new MyLinkedList()
obj.addAtHead(2)
obj.addAtTail(3)
obj.addAtIndex(0, 1)
var param_1 = obj.get(1)
console.log(param_1)
obj.deleteAtIndex(1)
console.log(obj)

结果如下:

MyLinkedList {
  head: ListNode { val: 1, next: ListNode { val: 3, next: null } },
  rear: ListNode { val: 3, next: null },
  len: 2
}

Finish!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值