-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Linked List.py
51 lines (39 loc) · 1.19 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
42
43
44
45
46
47
48
49
50
51
# Time complexity - O(N)
# Space complexity - 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]:
current = head
new = ptr = None
while current != None:
ptr = current
current = current.next
ptr.next = new
new = ptr
head = new
return head
# Time complexity - O(N)
# Space complexity - O(N)
# 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]:
current = head
new = ptr = None
return self.returnReverse(current,new,ptr)
def returnReverse(self,current,new,ptr):
if current is None:
return new
else:
ptr = current
current = current.next
ptr.next = new
new = ptr
return self.returnReverse(current,new,ptr)