From 614f985f1a2135a59c514ffdb638852141e3f573 Mon Sep 17 00:00:00 2001 From: marina <138340846+bt3gl-cryptography@users.noreply.github.com> Date: Mon, 31 Jul 2023 12:21:30 -0700 Subject: [PATCH] Create reverse_linked_list.py --- linked_lists/reverse_linked_list.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 linked_lists/reverse_linked_list.py diff --git a/linked_lists/reverse_linked_list.py b/linked_lists/reverse_linked_list.py new file mode 100644 index 0000000..fde6bdc --- /dev/null +++ b/linked_lists/reverse_linked_list.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# author: bt3gl + +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + + +def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]: + + if (not head) or (not head.next): + return head + + new_head = reverse_list(head.next) + head.next.next = head + head.next = None + + return new_head