From b16196e810a33189b55ccf86897735cd0dfb41da Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com> Date: Mon, 7 Aug 2023 15:50:35 -0700 Subject: [PATCH] Update reverse_linked_list_II.py --- linked_lists/reverse_linked_list_II.py | 27 +++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/linked_lists/reverse_linked_list_II.py b/linked_lists/reverse_linked_list_II.py index 667c3ce..0692312 100644 --- a/linked_lists/reverse_linked_list_II.py +++ b/linked_lists/reverse_linked_list_II.py @@ -2,6 +2,7 @@ # -*- coding: utf-8 -*- # author: bt3gl + class Node: def __init__(self, val=0, next): self.val = val @@ -10,17 +11,17 @@ class Node: def reverse_list(head: Optional[Node]) -> Optional[Node]: - if head is None: - return head - - final_head = head - - while head.next: - - new_node = head.next - head.next = new_node.next - new_node.next = final_head - final_head = new_node - - return final_head + if head is None: + return head + + prev = None + curr = head + while curr: + next_temp = curr.next // save the pointer for the next node so we can continue the loop + curr.next = prev // revert the list + prev = curr // save for the next node revert + curr = next_temp // receive the pointer for the next node so we can continue the loop + + return prev +