Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit871212d

Browse files
authored
Create 20-206. Reverse Linked List
1 parentb9c49ec commit871212d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎20-206. Reverse Linked List

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
Iterative Solution:
2+
class Solution:
3+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
4+
prev, curr = None, head
5+
6+
while curr:
7+
nxt = curr.next # save next
8+
curr.next = prev # add prev element to current's next
9+
prev = curr # increment prev
10+
curr = nxt # increment curr
11+
return prev # curr will be at NULL and prev will be the last node\
12+
13+
14+
15+
Recursive Solution:
16+
class Solution:
17+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
18+
19+
def recursion(prev, curr):
20+
if not curr:
21+
return prev
22+
23+
tail = recursion(curr, curr.next)
24+
curr.next = prev
25+
26+
return tail
27+
28+
return recursion(None, head)

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp