61. Rotate List

개꡴·2024λ…„ 6μ›” 28일

leetcode

λͺ©λ‘ 보기
43/51
  • python3

πŸ“Ž Problem

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

Example 1:

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

Example 2:

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 * 109

Plan Solution

  1. Count the lenght of the linked list.
  2. Adjust the number of rotations.
  3. Link with the fisrt and head node.
  4. Move step one by one.

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if not head or not head.next or k == 0:
            return head
        
        # 1. 전체 λ…Έλ“œ 수 카운트
        length = 1
        current = head
        while current.next:
            current = current.next
            length += 1
        
        # 2. νšŒμ „ 횟수 μ‘°μ •
        k = k % length
        if k == 0:
            return head
        
        # 3. 리슀트 끝과 μ‹œμž‘ μ—°κ²°
        current.next = head
        
        # 4. μƒˆλ‘œμš΄ ν—€λ“œλ₯Ό μ°ΎκΈ° μœ„ν•΄ 뢄리 지점을 κ²°μ •
        steps_to_new_head = length - k
        new_tail = head
        for _ in range(steps_to_new_head - 1):
            new_tail = new_tail.next
        
        # 5. μƒˆλ‘œμš΄ ν—€λ“œ μ„€μ • 및 리슀트 뢄리
        new_head = new_tail.next
        new_tail.next = None
        
        return new_head

Result

  • Time Complexity : O(n)
  • Space Complexity : O(1)
profile
μ•Œμ­λ‹¬μ­ν˜€μš”

0개의 λŒ“κΈ€