mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update reverse_linked_list_II.py
This commit is contained in:
parent
3024f285e5
commit
b16196e810
@ -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
|
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user