Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

61. 旋转链表 #21

Open
webVueBlog opened this issue Aug 31, 2022 · 0 comments
Open

61. 旋转链表 #21

webVueBlog opened this issue Aug 31, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

61. 旋转链表

Description

Difficulty: 中等

Related Topics: 链表, 双指针

给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k个位置。

示例 1:

输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]

示例 2:

输入:head = [0,1,2], k = 4
输出:[2,0,1]

提示:

  • 链表中节点的数目在范围 [0, 500]
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 109

Solution

Language: JavaScript

/**
 * 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 (k === 0 || !head || !head.next) {
        return head
    }

    let len = 1
    let cur = head
    while (cur.next) {
        cur = cur.next
        len++;
    }

    cur.next = head
    k = len - k % len
    
    while (k--) {
        cur = cur.next
    }
    head = cur.next
    cur.next = null
    return head
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant