61. 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
    
        """
        if head is None or head.next is None or k is 0: return head 
        n=1
        curr=head 
        #find the length of the list n 
        while curr.next:
            n+=1 
            curr=curr.next
        if k%n==0: return head 
        #connect the tail with the head     
        curr.next=head
        
        i=0
        tail=head
        #break the new tail and find head 
        while i <(n-k%n-1):
            tail=tail.next
            i+=1
        head=tail.next
        tail.next=None 
        return head 
        
        
           
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容