Skip to content

Commit cede840

Browse files
week 7: Reverse Linked List
1 parent b885adc commit cede840

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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+
# time complexity: O(n) / memory complexity: O(n)
9+
stack = []
10+
current = head
11+
while current:
12+
stack.append(current.val)
13+
current = current.next
14+
15+
dummy_head = ListNode()
16+
current = dummy_head
17+
while stack:
18+
current.next = ListNode(val=stack.pop(), next=None)
19+
current = current.next
20+
return dummy_head.next

0 commit comments

Comments
 (0)