본문 바로가기
LeetCode

[LeetCode] 61. Rotate List

by JungSeung 2024. 1. 9.
728x90

https://leetcode.com/

Given the head of a linked list, rotate the list to the right by k places.

 

Example 1:

출처 : https://leetcode.com/problems/rotate-list/

Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]

 

Example 2:

출처 : https://leetcode.com/problems/rotate-list/

Input: head = [0,1,2], k = 4
Output: [2,0,1]

 

Constraints:

  • The number of nodes in the list is in the range [0, 500].
  • -100 <= Node.val <= 100
  • 0 <= k <= 2 * 10^9

 

Code :

var rotateRight = function(head, k) {
    // 예외 처리: 헤드가 없거나 회전할 횟수가 0인 경우
    if (!head || k === 0) return head;

    // 연결 리스트의 길이 계산
    let length = 1;
    let current = head;
    while (current.next) {
        current = current.next;
        length++;
    }

    // 연결 리스트를 순환 리스트로 만듦
    current.next = head;

    // k 값이 length보다 큰 경우를 대비하여 나머지 연산
    k = k % length;

    // 오른쪽으로 회전하는 동안 현재 노드를 이동시킴
    for (let i = 0; i < length - k; i++) {
        current = current.next;
    }

    // 새로운 헤드 노드 설정 및 기존의 연결 리스트 끊어줌
    let newHead = current.next;
    current.next = null;

    return newHead;
};

 

Solutions Code :

var rotateRight = function (head, k) {
    // 예외 처리: 빈 연결 리스트인 경우 그대로 반환
    if (!head) return head;

    let count = 0,
        ptr = head;

    // Step 1: 연결 리스트의 노드 수를 세기
    while (ptr) {
        count++;
        ptr = ptr.next;
    }

    // Step 2: 회전 횟수를 노드 수로 나눈 나머지로 갱신
    k = k % count;
    let prev = head;
    ptr = head;

    // Step 3: 한 포인터를 k 만큼 이동
    while (k--) {
        ptr = ptr.next;
    }

    // Step 4: 실제 회전을 수행하는 부분
    while (ptr.next) {
        prev = prev.next;
        ptr = ptr.next;
    }

    // Step 5: 헤드와 마지막 노드를 수정하여 회전 결과 반환
    ptr.next = head;
    head = prev.next;
    prev.next = null;
    return head;
};

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 63. Unique Paths II  (0) 2024.01.12
[LeetCode] 62. Unique Paths  (0) 2024.01.12
[LeetCode] 60. Permutation Sequence  (0) 2023.12.29
[LeetCode] 59. Spiral Matrix II  (0) 2023.12.29
[LeetCode] 58. Length of Last Word  (0) 2023.12.28