Skip to content

Commit bb0a922

Browse files
committed
Rotate Linked List
1 parent b18a342 commit bb0a922

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Rotate_Linked_List.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Given a linked list, rotate the list to the right by k places, where k is non-negative.
2+
#
3+
# Example 1:
4+
#
5+
# Input: 1->2->3->4->5->NULL, k = 2
6+
# Output: 4->5->1->2->3->NULL
7+
# Explanation:
8+
# rotate 1 steps to the right: 5->1->2->3->4->NULL
9+
# rotate 2 steps to the right: 4->5->1->2->3->NULL
10+
# Example 2:
11+
#
12+
# Input: 0->1->2->NULL, k = 4
13+
# Output: 2->0->1->NULL
14+
# Explanation:
15+
# rotate 1 steps to the right: 2->0->1->NULL
16+
# rotate 2 steps to the right: 1->2->0->NULL
17+
# rotate 3 steps to the right: 0->1->2->NULL
18+
# rotate 4 steps to the right: 2->0->1->NULL
19+
20+
21+
class ListNode:
22+
def __init__(self, x):
23+
self.val = x
24+
self.next = None
25+
26+
27+
class Solution:
28+
def rotateRight(self, head, k):
29+
if not head:
30+
return head
31+
if not head.next:
32+
return head
33+
34+
length = 0
35+
curr = head
36+
while curr:
37+
length += 1
38+
curr = curr.next
39+
40+
k = k % length
41+
slow = fast = head
42+
43+
for _ in range(k):
44+
fast = fast.next
45+
46+
while fast.next:
47+
slow = slow.next
48+
fast = fast.next
49+
50+
fast.next = head
51+
head = slow.next
52+
slow.next = None
53+
54+
return head

0 commit comments

Comments
 (0)