-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206-Reverse-Linked-List.py
More file actions
52 lines (35 loc) · 993 Bytes
/
Copy path206-Reverse-Linked-List.py
File metadata and controls
52 lines (35 loc) · 993 Bytes
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
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
# region Recursive Solution
class Solution:
# Space O(n)
# Time O(n)
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.helper(head, None)
def helper(
self, head: Optional[ListNode], prev: Optional[ListNode]
) -> Optional[ListNode]:
if not head:
return prev
else:
nextHead = head.next
head.next = prev
return self.helper(nextHead, head)
# endregion
# region Iterative Solution
class Solution:
# Space O(1)
# Time O(n)
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = None
while head:
ptr = head.next
head.next = cur
cur = head
head = ptr
return cur
# endregion