61. 旋转链表

<环形链表>

题目

给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。

示例 1:

输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

示例 2:

输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL

我的思路 

class Solution(object):
        '''
        1.找到分割点:即chuck的位置。
            a.求出总长度leng
            b.chuck = leng - (k mod leng) - 1
        2.分割点之前的链表和分割点之后的链表换个位置
        3.OK
        例如 1,2,3,4,5 k=2  ->  1,2,3(chuck),4,5  ->  4,5,1,2,3
        
        '''
    def rotateRight(self, head, k):
        if not head or not head.next or not k:
            return head
        
        node = head
        leng = 0 
        while node:
            leng+=1
            tail = node
            node = node.next
        node = head
                
        #特别的,如果右移回原来的位置,则原样输出
        if k % leng == 0:
            return head
                        
        #移动到chuck的位置
        for i in range( leng - (k%leng) - 1 ):
            node = node.next
                        
        #进行拼接
        chuck = node
        newhead = node.next
        tail.next = head
        chuck.next = None
                
        return newhead

题解

 环形链表解题,关键在于求出分割点

总结

原文地址:https://www.cnblogs.com/remly/p/11572130.html