JavaScript关于链表的所有操作

//节点类
class Node{
    constructor(data){
        this.data = data;
        this.prev = null;
        this.next = null;
    }
}
//单链表类
class SingleList{
    constructor(){
        this.size = 0;
        this.head = new Node('head');//表头节点
        this.currNode = ''//当前的节点指针
    }
    //判断当前列表是否为null
    isEmpty(){
      return this.size === 0
    }
    //获取单链表的长度
    getLength(){
        return this.size
    }
    // 显示当前节点
    showNode(){
        console.log(this.currNode.data)
    }
    //遍历单链表
    displayList(){
        let result = ''
        let currNode = this.head
        while(currNode){
            result += currNode.data;
            currNode = currNode.next
            if(currNode){
                result += '->'
            }
        }
        console.log(result)
    }
    //获取单链表的最后一个节点
    findList(){
        let currNode = this.head
        while(currNode.next){
            currNode = currNode.next
        }
        return currNode
    }
    //倒序遍历单链表
    lastDisplay(){
        let currNode = this.findList();
        let result = ''
        while(currNode){
            result += currNode.data;
            currNode = currNode.prev;
            if(currNode){
                result +='->'
            }
        }
        console.log(result)
    }
    //在列表中查找某元素
    findNode(item){
        let currNode = this.head
        while((item) && (item !== currNode.data)){
            currNode = currNode.next
        }
        return currNode
    }
    //在列表中插入节点
    insertNode(item,element){
        let itemNode = this.findNode(item)
        if(!itemNode){
            return
        }
        let newNode = new Node(element)
        newNode.next = itemNode.next
        itemNode.next = newNode
        return newNode
        this.size++
    }
    //在链表尾部添加节点
    appendNode(element){
        let currNode = this.findList()
        let newNode = new Node(element)
        currNode.next = newNode
        newNode.prev = currNode
        this.size++
    }
}
module.exports.SingleList = SingleList

测试代码如下:

var List = require('./singlelist')
let mylist = new List.SingleList();
let arr = [3, 4, 5, 6, 7, 8, 9,10,22];
for(let i=0; i<arr.length; i++){
    mylist.appendNode(arr[i]);
}
mylist.displayList();
mylist.lastDisplay();

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值