forked from yingl/LintCodeInPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate_list.py
More file actions
27 lines (26 loc) · 815 Bytes
/
rotate_list.py
File metadata and controls
27 lines (26 loc) · 815 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# -*- coding: utf-8 -*-
class Solution:
# @param head: the list
# @param k: rotate to the right k places
# @return: the list after rotation
def rotateRight(self, head, k):
# write your code here
if not head:
return head
list_len = 0
tail = None
node = head
while node: # 找到链表的尾部节点并统计链表长度
list_len += 1
tail = node
node = node.next
shift = k % list_len
if shift == 0:
return head
new_tail = head
for i in xrange(list_len - shift-1):
new_tail = new_tail.next
new_head = new_tail.next # 找到新的head
tail.next = head # tail指向原来的head
new_tail.next = None
return new_head