Skip to content

Commit 62983fb

Browse files
committed
Rotate List
1 parent 0ec4e4e commit 62983fb

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
3535
|-----|-------| -------- | ---- | ------|------------|---|-----|
3636
|83|[Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/#/description)| [Python](./linkedlist/deleteDuplicates.py) | _O(n)_| _O(1)_ | Easy | ||
3737
|148|[Sort List](https://leetcode.com/problems/sort-list/#/description)| [Python](./linkedlist/sortList.py) | _O(nlogn)_| _O(1)_ | Medium | ||
38+
|61|[Rotate List](https://leetcode.com/problems/rotate-list/#/description)| [Python](./linkedlist/rotateRight.py) | _O(n)_| _O(1)_ | Medium | ||

linkedlist/rotateRight.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Author: Yu Zhou
2+
# 61. Rotate List
3+
4+
# Given a list, rotate the list to the right by k places, where k is non-negative.
5+
#
6+
# For example:
7+
# Given 1->2->3->4->5->NULL and k = 2,
8+
# return 4->5->1->2->3->NULL.
9+
10+
# Time: O(n)
11+
# Space: O(1)
12+
13+
# 思路
14+
# 先Pad距离,然后用Mod测量周期,最后将之前切断的两节链表链接起来
15+
16+
# ****************
17+
# Final Solution *
18+
# ****************
19+
class Solution(object):
20+
def rotateRight(self, head, k):
21+
#Edge
22+
if not head or not head.next:
23+
return head
24+
25+
cur, count = head, 0
26+
27+
#Count Length for modular operation
28+
while cur:
29+
cur = cur.next
30+
count += 1
31+
mod = k % count
32+
33+
#Edge2
34+
if k == 0 or mod == 0:
35+
return head
36+
37+
slow = fast = head
38+
for _ in xrange(mod):
39+
fast = fast.next
40+
41+
# Use fast.next here so fast point doesn't reach Null
42+
while fast.next:
43+
slow = slow.next
44+
fast = fast.next
45+
46+
newHead = slow.next
47+
fast.next = head
48+
slow.next = None
49+
50+
return newHead
51+
52+
# ***************************************
53+
# The following code is an fail attempt *
54+
# ***************************************
55+
class Solution(object):
56+
def rotateRight(self, head, k):
57+
if not head:
58+
return None
59+
60+
slow = fast = head
61+
62+
for _ in xrange(k):
63+
fast = fast.next
64+
65+
prev = None
66+
while fast:
67+
prev = slow
68+
slow = slow.next
69+
fast = fast.next
70+
71+
prev.next = None
72+
newHead = cur = slow
73+
74+
while cur.next:
75+
cur = cur.next
76+
77+
cur.next = head
78+
return newHead

0 commit comments

Comments
 (0)