File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ Given a list, rotate the list to the right by k places, where k is non-negative.
3+
4+ For example:
5+ Given 1->2->3->4->5->NULL and k = 2,
6+ return 4->5->1->2->3->NULL.
7+ '''
8+ # Definition for singly-linked list.
9+ class ListNode(object):
10+ def __init__(self, x):
11+ self.val = x
12+ self.next = None
13+
14+ class Solution(object):
15+ def rotateRight(self, head, k):
16+ ref = head
17+ length = 0
18+
19+ while head:
20+ head = head.next
21+ length += 1
22+
23+ if length < 2 or k % length == 0:
24+ return ref
25+
26+ prev = None
27+ current = ref
28+ for _ in xrange(length - (k % length)):
29+ prev, current = current, current.next
30+
31+ prev.next = None
32+ new_head = current
33+
34+ if not current:
35+ return ref
36+ while current.next:
37+ current = current.next
38+ current.next = ref
39+
40+ return new_head
You can’t perform that action at this time.
0 commit comments