solution Linked List 1#1784
Conversation
Reverse a LinkedList (reverse_linked_list.py)Your solution correctly reverses the linked list using recursion. Well done on implementing the recursive approach! Here are some points for improvement:
Overall, your solution is correct and demonstrates understanding of recursion. However, for production code or large inputs, the iterative approach is preferred. You might want to implement both as suggested in the follow-up. VERDICT: PASS Remove nth node (remove_nth_node.py)Your approach of using two pointers (fast and slow) with a dummy node is a good idea to handle the one-pass requirement and edge cases. However, there is a mistake in the first loop: you are moving the Here's how to correct it:
Alternatively, you can move the fast pointer Corrected code snippet: temp = ListNode(0)
temp.next = head
first = temp
second = temp
# Move second pointer n steps ahead
for i in range(n):
second = second.next
# Move both until second reaches the last node
while second.next:
first = first.next
second = second.next
# Remove the nth node
first.next = first.next.next
return temp.nextThis way, when second is at the last node (not null), first is at the node before the one to be removed. This handles all cases including when n equals the length of the list (removing the head). Also, note that in your code, you have Keep up the good work in trying to optimize for one pass! Just pay attention to the exact number of steps needed. VERDICT: NEEDS_IMPROVEMENT Cycle in linked list (linked_list_cycle.py)Your solution is correct and efficient. Well done! Here are a few suggestions for improvement:
But your current approach is fine. Here's a slightly revised version without the flag: class Solution(object):
def detectCycle(self, head):
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
fast = head
while fast != slow:
fast = fast.next
slow = slow.next
return fast
return NoneThis version is more concise and avoids the extra variable. Overall, your solution is correct and efficient. Keep up the good work! VERDICT: PASS |
No description provided.