MCPcopy Create free account
hub / github.com/HuberTRoy/leetCode / rotateRight

Method rotateRight

Array/RotateList.py:51–97  ·  view source on GitHub ↗

:type head: ListNode :type k: int :rtype: ListNode

(self, head, k)

Source from the content-addressed store, hash-verified

49class Solution(object):
50
51 def rotateRight(self, head, k):
52 """
53 :type head: ListNode
54 :type k: int
55 :rtype: ListNode
56 """
57 if not k or not head:
58 return head
59
60 def getLength(node):
61 length = 0
62
63 while node:
64 node = node.next
65 length += 1
66
67 return length
68
69 length = getLength(head)
70 k = k % length
71
72 slow = head
73 fast = head
74
75 while k > 0:
76 fast = fast.next
77
78 k -= 1
79
80 while fast.next:
81 slow = slow.next
82 fast = fast.next
83
84 rotate_head = slow.next
85
86 if not rotate_head:
87 return head
88
89 slow.next = None
90
91 _rotate_head = rotate_head
92 while _rotate_head.next:
93 _rotate_head = _rotate_head.next
94
95 _rotate_head.next = head
96
97 return rotate_head
98

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected