-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206_Reverse_Linked_List.py
More file actions
38 lines (31 loc) · 1004 Bytes
/
Copy path206_Reverse_Linked_List.py
File metadata and controls
38 lines (31 loc) · 1004 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
# 2 Possible Solutions
# 1. Iterative Approach
# 2. Recursive Approach
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
# Iterative
# Time: O(N), Space: O(1)
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
previousNode = None
currentNode = head
while currentNode:
nextNode = currentNode.next
currentNode.next = previousNode
previousNode = currentNode
currentNode = nextNode
return previousNode
# Recursive
# Time: O(N), Space: O(N)
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
newHead = head
if head.next:
newHead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newHead