-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08_RotateAList.py
More file actions
40 lines (33 loc) · 1.09 KB
/
08_RotateAList.py
File metadata and controls
40 lines (33 loc) · 1.09 KB
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
# Question link - https://leetcode.com/problems/rotate-list/description/?envType=study-plan-v2&envId=top-interview-150
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
length ,tail = 1, head
# If empty
if (head is None or k == 0):
return head
# Length of LL
while tail.next is not None:
length += 1
tail = tail.next
# If k is equivalent to length
if (k % length == 0):
return head
k = k % length
tail.next = head
newLastNode = self.findLastNode(head , length - k)
head = newLastNode.next
newLastNode.next = None
return head
def findLastNode(self, temp , k):
count = 1
while temp is not None:
if count == k:
return temp
count += 1
temp = temp.next
return temp