当前位置: 首页 > Web前端 > JavaScript

第3-100天算法-Javascript模拟实现旋转链表

时间:2023-03-27 10:15:40 JavaScript

今天是LeetCode算法题https://leetcode-cn.com/probl...解题前需要了解算法结构:1.链表的结构list/***单向链表的定义。*functionListNode(val,next){*this.val=(val===undefined?0:val)*this.next=(next===undefined?null:next)*}*/结构类似于如下:{value:val,next:{value:val2,next:null}}2.输入头其实不是数组的形式,而是上面的结构然后根据结构模拟链表。思路是先形成闭环,再打断;解还是有快慢双指针的;这个传说很清楚;https://leetcode-cn.com/probl...模仿代码如下:varrotateRight=function(head,k){//ListNode的节点结构为{value:val,next:{value:val2,next:null}}if(!head||!head.next||!k){returnhead}//获取链表长度letlen=1lettmp=headwhile(tmp.next){tmp=tmp.nextlen++}//形成闭环tmp.next=headletgap=len-k%len//寻找分裂节点while(gap){tmp=tmp.nextgap--}letres=tmp.nexttmp.next=null返回res};