Scribbling

LeetCode: 61. Rotate List 본문

Computer Science/Coding Test

LeetCode: 61. Rotate List

focalpoint 2021. 9. 24. 16:40
# 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:
            return
        
        count, cur, prv = 0, head, None
        while cur != None:
            prv = cur
            count += 1
            cur = cur.next
            
        tail = prv
        
        k %= count
        if k == 0:
            return head
        
        cur = head
        for i in range(count - k - 1):
            cur = cur.next
        
        new_head = cur.next
        cur.next = None
        tail.next = head
        return new_head

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 63. Unique Paths II  (0) 2021.09.24
LeetCode: 62. Unique Paths  (0) 2021.09.24
LeetCode: 60. Permutation Sequence  (0) 2021.09.24
LeetCode: 59. Spiral Matrix II  (0) 2021.09.24
LeetCode: 53. Maximum Subarray  (0) 2021.09.24