LeetCode-61. Rotate List

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

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.

Solution

# 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
        """
        if not head or not head.next or k == 0:
            return head
        tail = head
        n = 1
        while tail.next:
            tail = tail.next
            n += 1
            
        k = k%n
        slow = head
        fast = head
        newHead = ListNode(None)
        for i in range(k):
            fast = fast.next
        while fast.next:
            slow = slow.next
            fast = fast.next
        fast.next = head
        newHead.next = slow.next
        slow.next = None
        return newHead.next
posted @ 2016-11-21 17:01  BinWone  阅读(124)  评论(0编辑  收藏  举报