Back to course home
0% completed
Vote For New Content
My python solution. O(n). Basically the same approach as the solution. Avoids potential circular loop.
Eric Imho Jang
Aug 1, 2024
#class Node: # def __init__(self, value, next=None): # self.val = value # self.next = next class Solution: def rotate(self, head, rotations): if rotations == 0: return head # get length of linked list and get necessary rotation length = 0 current, previous = head, None while current: length += 1 current = current.next remainder = rotations % length if remainder == 0: return head newHeadIndex = length - remainder current = head i = 0 newHead = None while current: next = current.next # find and break the link before newHeadNode if i == newHeadIndex - 1: current.next = None # store new head node elif i == newHeadIndex: newHead = current previous = current current = next i += 1 # link the end with original head and replace head with new head previous.next = head head = newHead return head
0
0
Comments
Comments
On this page