Skip to content

Commit 1afc4b8

Browse files
committed
leetcode.com 61. Rotate List
문제 링크: https://leetcode.com/problems/rotate-list
1 parent f33392a commit 1afc4b8

File tree

1 file changed

+42
-0
lines changed
  • leetcode.com 61. Rotate List

1 file changed

+42
-0
lines changed

leetcode.com 61. Rotate List/main.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import Optional
2+
3+
4+
# Definition for singly-linked list.
5+
class ListNode:
6+
def __init__(self, val=0, next=None):
7+
self.val = val
8+
self.next = next
9+
10+
11+
class Solution:
12+
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
13+
# linked list length is 1
14+
if head is None or head.next is None:
15+
return head
16+
17+
length = 0
18+
node = head
19+
while node:
20+
length += 1
21+
node = node.next
22+
23+
k = k % length
24+
25+
# from here, linked list length is 2 at least
26+
for _ in range(k):
27+
tail = self.get_tail(head)
28+
tail.next = head
29+
head = tail
30+
31+
return head
32+
33+
def get_tail(self, node: Optional[ListNode]):
34+
prev = node
35+
node = node.next
36+
37+
while node.next:
38+
prev = node
39+
node = node.next
40+
41+
prev.next = None
42+
return node

0 commit comments

Comments
 (0)