Iterative, easy to understand Python solution


  • 0
    T
    class Solution(object):
        def rotateRight(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if not k or not head:
                return head
            list_len, cur, last = 0, head, None
            while cur:
                last, cur, list_len = cur, cur.next, list_len + 1
            k %= list_len
            if k:
                k = list_len - k
                pre, cur = None, head
                for _ in xrange(k):
                    pre, cur = cur, cur.next
                pre.next = None
                last.next, head = head, cur
            return head
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.