leetcode之Rotate List

来源:互联网 发布:php远程代码执行漏洞 编辑:程序博客网 时间:2024/05/22 09:42
就是将倒数的几个数放到前面,再把前面的数放到后面去接起来。代码如下:
# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def rotateRight(self, head, k):        """        :type head: ListNode        :type k: int        :rtype: ListNode        """        if not head:            return head        length = 0        head1 = head        while head1.next:            length += 1            head1 = head1.next        length = length + 1        k = k % length        head2 = head        head1.next = head2        for i in range(length - k):            if i == length - k - 1:                head =head.next                head2.next = None            else:                head2 = head2.next                head = head.next        return head

0 0