Skip to content

Commit 955d3d2

Browse files
committed
re-solved reverse linked list
1 parent a269aff commit 955d3d2

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

reverse-linked-list/SamTheKorean.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,26 @@
22
# Space complexity : O(n)
33
class Solution:
44
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
5+
# Return None when head is None
6+
if not head:
7+
return None
8+
59
stack = []
610
node = head
711

812
while node:
9-
stack.append(node.val)
13+
stack.append(node)
1014
node = node.next
1115

16+
head = stack.pop()
1217
node = head
13-
while node:
14-
node.val = stack.pop()
18+
19+
# End the loop when stack is empty
20+
while stack:
21+
node.next = stack.pop()
1522
node = node.next
1623

24+
# Set the last node's next to None to indicate the end of the reversed list
25+
node.next = None
26+
1727
return head

0 commit comments

Comments
 (0)