Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitdb16c2a

Browse files
add 1 leetcodes
1 parent16a250a commitdb16c2a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

‎leetcode/61. Rotate List

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp