Skip to content

Commit 5ca7bd6

Browse files
committed
solve: reverseLinkedList
1 parent 89edeec commit 5ca7bd6

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

reverse-linked-list/yolophg.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Time Complexity: O(n)
2+
# Space Complexity: O(1)
3+
4+
class Solution:
5+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
6+
prev = None
7+
# to traverse the original list, starting from head
8+
current = head
9+
while current:
10+
# reverse the link and move to the next node
11+
prev, prev.next, current = current, prev, current.next
12+
13+
# prev is now the head of the reversed list
14+
return prev

0 commit comments

Comments
 (0)