leetcode 61Rotate List

来源:互联网 发布:ubuntu配置lamp环境 编辑:程序博客网 时间:2024/04/24 04:08
# 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
        n=self.getSize(head)
        k%=n
        dummy=ListNode(0)
        dummy.next=head
        p=head
        for i in range(k):
            p=p.next
        for j in range(n-k-1):
            p=p.next
            head=head.next
        p.next=dummy.next
        dummy.next=head.next
        head.next=None
        return dummy.next
    def getSize(self,head):

        n=0

        while head:
           head=head.next
           n+=1

        return n

https://www.youtube.com/watch?v=7OBo9fBp1FE

0 0