forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse.py
More file actions
60 lines (46 loc) · 1.3 KB
/
reverse.py
File metadata and controls
60 lines (46 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Reverse Linked List
Reverse a singly linked list. Both iterative and recursive solutions are
provided.
Reference: https://leetcode.com/problems/reverse-linked-list/
Complexity:
Time: O(n)
Space: O(1) iterative, O(n) recursive
"""
from __future__ import annotations
def reverse_list(head: object | None) -> object | None:
"""Reverse a singly linked list iteratively.
Args:
head: Head node of the linked list (must have .next attr).
Returns:
The new head of the reversed list.
Examples:
>>> reverse_list(None) is None
True
"""
if not head or not head.next:
return head
prev = None
while head:
current = head
head = head.next
current.next = prev
prev = current
return prev
def reverse_list_recursive(head: object | None) -> object | None:
"""Reverse a singly linked list recursively.
Args:
head: Head node of the linked list (must have .next attr).
Returns:
The new head of the reversed list.
Examples:
>>> reverse_list_recursive(None) is None
True
"""
if head is None or head.next is None:
return head
rest = head.next
head.next = None
reversed_rest = reverse_list_recursive(rest)
rest.next = head
return reversed_rest