5/29/2020

[LeetCode] 61. Rotate List

Problem : https://leetcode.com/problems/rotate-list/

Step 1.  Link the tail and head element to make a circuit linked list.
Step 2.  Rotate the list to right by k places equal to move head to position Total - k % Total 
Step 3.  Move to the new head and break the circuit linked list

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        
        if not head:
            return None
        
        p = head
        total = 1
        
        while p.next:
            total += 1
            p = p.next
        
        # link th tail and head
        p.next = head
        
        # find the new head position
        k = total - (k % total) - 1
        
        p = head
        while k > 0:
            p = p.next
            k -= 1
        
        head = p.next
        p.next = None
        
        
        return head

No comments:

Post a Comment