We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 0d7115a + dde78d8 commit 5c3afafCopy full SHA for 5c3afaf
1 file changed
reverse-linked-list/jylee2033.py
@@ -0,0 +1,27 @@
1
+# Definition for singly-linked list.
2
+# class ListNode:
3
+# def __init__(self, val=0, next=None):
4
+# self.val = val
5
+# self.next = next
6
+class Solution:
7
+ def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
8
+ # Handle empty list
9
+ # if head is None:
10
+ # return head
11
+
12
+ prev = None
13
+ cur = head # Start from the head node
14
15
+ # Traverse until the last node
16
+ while cur is not None:
17
+ nxt = cur.next # Store next node
18
+ cur.next = prev # Reverse the link
19
+ prev = cur # Move prev forward
20
+ cur = nxt # Move cur forward
21
22
+ # Handle the last node
23
+ # cur.next = prev
24
+ return prev
25
26
+# Time Complexity: O(n)
27
+# Space Complexity: O(1)
0 commit comments