Skip to content

Commit 330eded

Browse files
committed
week 7 reverse-linked-list
1 parent f333b6b commit 330eded

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
"""
8+
Time complexity O(n)
9+
Space complexity O(1)
10+
"""
11+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
12+
if not head or not head.next:
13+
return head
14+
15+
node = head.next
16+
prev = head
17+
prev.next = None
18+
19+
while node:
20+
next_node = node.next
21+
node.next = prev
22+
prev = node
23+
node = next_node
24+
25+
return prev

0 commit comments

Comments
 (0)