작심삼일

[LeetCode] 61 | Rotate List | Python 본문

스터디/코테

[LeetCode] 61 | Rotate List | Python

yun_s 2022. 3. 11. 10:43
728x90
반응형

문제 링크: https://leetcode.com/problems/rotate-list/


문제

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


조건

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

내 풀이

주어진 리스트(head)의 길이를 파악한 후, 이를 이용해 k의 숫자를 줄인다. (k %= count)

왼쪽으로 rotate할 경우에는 이를 그대로 사용해도 되지만, 오른쪽으로 rotate 해야하므로 count-k를 k로 재정의한다.

이 때, k가 head의 길이와 같다면 전체 rotate한 후 그대로 return되기 때문에 바로 head를 return한다.

앞에서부터 k번째 노드를 기준으로 자른 후, 뒤 리스트를 앞으로 붙이면 된다.


코드

# 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:   return head
        nhead = head
        count = 1
        
        while nhead.next:
            count += 1
            nhead = nhead.next
        k %= count
        k = count - k
        if k == count:  return head
        
        nhead = head
        while k > 1:
            k -= 1
            nhead = nhead.next
        
        ans = nhead.next
        nhead.next = None
        
        findTail = ans
        
        while findTail.next:
            findTail = findTail.next
        findTail.next = head
        
        return ans
728x90
반응형
Comments