'How do pointers in linked lists relate to the lists themselves?
I am working on leetcode #61, on rotating the linked list. I understand many of the solutions online, but I don't understand why the solution I came up with doesn't work. The logic seems simple: get two pointers, take one to the last node and the other one to the last-but-one node, then change the next
nodes to the head and None
respectively. Do this as many times as needed and return the resulting list. However, some nodes get lost in the way, and I can't figure out why this is happening. Here is my code:
class Solution:
def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
prev = head
curr = prev.next
while k > 0:
while curr.next:
prev = curr
curr = curr.next
curr.next = head
prev.next = None
k -= 1
return curr
Can anybody explain to me where/what I am doing wrong?
Solution 1:[1]
First of all you have used nested loops, that will get you an n2 time complexity. Which will be sufficient to give you a TLE and your answer will not be accepted.
Coming back to your solution, the problem here is that your head
pointer is not updating(line number 9 of your code above
) due to which, after each iteration of the outer while
loop you will lose track of the node pointing your original header node, which will eventually make you loose the remaining nodes.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | enthusiast |