LintCode Q170 Rotate List in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2017年1月15日
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
28
29
30
31
32
33
34
35
36
37
38
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
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
# calculate length of linked list
if head is None:
return head
length = 1
current = head
while current.next:
length += 1
current = current.next
if length == 1:
return head
# find real shift number
k = k % length
if k == 0:
return head
# make a cercle for list
current.next = head
count = 0
current = head
previous = None
while count < length - k:
previous = current
current = current.next
count += 1
previous.next = None
return current
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。