forked from MiyabiTane/myLeetCode_
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path61_m_Rotate_List.py
55 lines (47 loc) · 1.29 KB
/
61_m_Rotate_List.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class ListNode:
def __init__(self, x):
self.val=x
self.next=None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if head == None or head.next == None:
return head
def count_length(head):
length = 0
if head.next == None:
return 1
while head.next != None:
length += 1
head = head.next
return length+1
count = head
length = count_length(count)
k %= length
if k == 0:
return head
remine = ListNode(0)
rem_dummy = remine
#頭のlen-k個をremineに。残りをheadに。
for i in range(length-k):
rem_dummy.next = ListNode(head.val)
head = head.next
rem_dummy = rem_dummy.next
#print("remine is ",remine)
#print("head is ",head)
dummy = head
#headのポインターを一番後ろに持ってくる
while head.next != None:
head = head.next
head.next = remine.next
return dummy
"""
solu=Solution()
init_list=ListNode(0)
init=init_list
for i in range(5):
init_list.next=ListNode(i+1)
init=init.next
print(init)
ans=solu.rotateRight(init, 2)
print(ans)
"""