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.
1 parent a269aff commit 955d3d2Copy full SHA for 955d3d2
reverse-linked-list/SamTheKorean.py
@@ -2,16 +2,26 @@
2
# Space complexity : O(n)
3
class Solution:
4
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
5
+ # Return None when head is None
6
+ if not head:
7
+ return None
8
+
9
stack = []
10
node = head
11
12
while node:
- stack.append(node.val)
13
+ stack.append(node)
14
node = node.next
15
16
+ head = stack.pop()
17
- while node:
- node.val = stack.pop()
18
19
+ # End the loop when stack is empty
20
+ while stack:
21
+ node.next = stack.pop()
22
23
24
+ # Set the last node's next to None to indicate the end of the reversed list
25
+ node.next = None
26
27
return head
0 commit comments