Update reverse_linked_list_II.py

This commit is contained in:
marina 2023-08-07 15:50:35 -07:00 committed by GitHub
parent 3024f285e5
commit b16196e810
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,6 +2,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# author: bt3gl # author: bt3gl
class Node: class Node:
def __init__(self, val=0, next): def __init__(self, val=0, next):
self.val = val self.val = val
@ -10,17 +11,17 @@ class Node:
def reverse_list(head: Optional[Node]) -> Optional[Node]: def reverse_list(head: Optional[Node]) -> Optional[Node]:
if head is None: if head is None:
return head return head
final_head = head prev = None
curr = head
while head.next: 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
new_node = head.next return prev
head.next = new_node.next
new_node.next = final_head
final_head = new_node
return final_head