嫣枝盎柳 發表於 2026-4-20 21:30:00

61 旋转链表

<h2 id="61-旋转链表">61 旋转链表</h2>
<pre><code class="language-js">/**
* Definition for singly-linked list.
* function ListNode(val, next) {
*   this.val = (val===undefined ? 0 : val)
*   this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
var rotateRight = function(head, k) {
    // 判断我们的这个节点是不是空的
    if(!head) return null;
    // 找到我们链表的尾节点,穿成环,获取到链表的长度,
    let cur=head,size=1;
    while(cur.next)cur=cur.next,size+=1;
    cur.next=head;
    // 找到第size-k个节点。然后将他断开
    for(let i=0;i&lt;size-k%size-1;i++){
      head=head.next;
    }
    cur=head.next;
    head.next=null;
    return cur;
};
</code></pre><br><br>
来源:https://www.cnblogs.com/KooTeam/p/19897381
頁: [1]
查看完整版本: 61 旋转链表