-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreverse_linked_list.py
41 lines (35 loc) · 1.04 KB
/
reverse_linked_list.py
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
#iterative appoach O(n) O(1)
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
temp = None
while head != None:
next = head.next
head.next = temp
temp = head
head = next
return temp
'''
#recursive implementation O(n) O(1)
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None:
return head
newHead = self.reverseList(head.next)
next_head = head.next
next_head.next = head
head.next = None
return newHead
'''
#but as always, recursive approach generates a little more cache, so more space needed