moonlightshadow123
6/26/2017 - 2:43 AM

61. Rotate List

  1. Rotate List
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        p = head
        if p == None:
            return 
        length = 1
        while p.next != None:
            p = p.next
            length += 1
        # Get the total number of nodes in the list.
        p.next = head
        # Make a circle.
        for i in range(length - k % length):
            # Jump len - k times.
            p = p.next
        # Break the cricle.
        head = p.next
        p.next = None
        return head

https://leetcode.com/problems/rotate-list/#/description

Given a list, rotate the list to the right by k places, where k is non-negative.

For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.