leetcode: 61. Rotate List

来源:互联网 发布:临漳干部网络管理系统 编辑:程序博客网 时间:2024/05/20 05:55

Q

Given a list, rotate the list to the right by k places, where k is non-negative.

Example:

Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL.

AC

# Definition for singly-linked list.class ListNode:    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 None        n = 0        cursor = head        while cursor:            cursor = cursor.next            n += 1        k = k%n        if k==0: return head        fast = slow = head        for i in range(k):            if fast:                fast = fast.next            else:                 break        preslow = None        prefast = None        while fast:            prefast = fast            fast = fast.next            preslow = slow            slow = slow.next        if preslow:            prefast.next = head            preslow.next = None            return slow        else:            return head# Time:  O(n)# Space: O(1)# Definition for singly-linked list.class ListNode:    def __init__(self, x):        self.val = x        self.next = None    def __repr__(self):        if self:            return "{} -> {}".format(self.val, repr(self.next))class Solution2(object):    def rotateRight(self, head, k):        """        :type head: ListNode        :type k: int        :rtype: ListNode        """        if not head or not head.next:            return head        n, cur = 1, head        while cur.next:            cur = cur.next            n += 1        cur.next = head        cur, tail = head, cur        for _ in xrange(n - k % n):            tail = cur            cur = cur.next        tail.next = None        return curif __name__ == "__main__":    head, head.next, head.next.next, head.next.next.next, head.next.next.next.next = ListNode(1), ListNode(2), ListNode(3), ListNode(4), ListNode(5)    print Solution().rotateRight(head, 2)