前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >双向链表[js实现] 【4】

双向链表[js实现] 【4】

作者头像
用户4793865
发布2023-01-12 13:11:11
3380
发布2023-01-12 13:11:11
举报
文章被收录于专栏:前端小菜鸡yym前端小菜鸡yym
get(positon)

用途: 获取相应位置的元素

思路

定义一个current和index初始都指向第一个节点。

image.png
image.png

current和index向后移,直到和position相等。然后把current对应节点的data返回即可。

image.png
image.png

编码

  • 首先是越界判断,小于零或者大于等于链表长度返回false
  • 定义变量,current和index。current指向head,index从0开始。
  • while循环向后寻找,每次执行完后给index进行+1。并将current的next赋值给current。
  • 直到current和position相等,跳出循环,返回current的data
代码语言:javascript
复制
 TwoWayLinkList.prototype.get = function (position) {
                // 越界判断
                if (position < 0 || position >= this.length) { return false }
                // 获取元素
                var current = this.head
                var index = 0
                while (index++ < position) {
                    current = current.next
                }
                return current.data
            }
复制代码

测试一下

代码语言:javascript
复制
   // 测试
        var list = new TwoWayLinkList()
        list.append('abc')
        list.append('bce')
        list.append('ghg')
        console.log(list.insert(0, 'insert'))
        console.log(list.insert(4, 'insert1'))
        console.log(list.insert(3, 'insert2'))
        console.log(list.toString())
        console.log(list.get(2))
image.png
image.png

效率分析

其实现在的get()方法的效率并不是很高。比如position为99,那么我们就需要从0一直找到99。对于单向链表只能从头开始找。但是双向链表可以根据就近原则,选择从前往后找,还是从后往前找。

  • this.length / 2 > position :从前向后遍历
  • this.length / 2 < position :从后向前遍历
  • 对于从后向前寻找的current初始指向tail,index为length-1(小标为长度-1)
  • 每次循环后减一

代码

代码语言:javascript
复制
  TwoWayLinkList.prototype.get = function (position) {
                // 越界判断
                if (position < 0 || position >= this.length) { return false }
               
                if (this.length / 2 >= position) {
                    // 获取元素
                    var current = this.head
                    var index = 0
                    while (index++ < position) {
                        current = current.next
                    }
                } else {
                    // 获取元素
                    var current = this.tail
                    // 元素的下标只到length-1
                    var index = this.length - 1
                    while (index-- > position) {
                        current = current.prev
                    }
                }

                return current.data
            }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-06-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 思路
  • 编码
  • 测试一下
  • 效率分析
    • 代码
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档