Skip to content

Commit 476be73

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 18.8 MB (38.13%)
1 parent 4ec57c5 commit 476be73

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</em>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" style="width: 542px; height: 222px;" />
6+
<pre>
7+
<strong>Input:</strong> head = [1,2,3,4,5]
8+
<strong>Output:</strong> [5,4,3,2,1]
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" style="width: 182px; height: 222px;" />
13+
<pre>
14+
<strong>Input:</strong> head = [1,2]
15+
<strong>Output:</strong> [2,1]
16+
</pre>
17+
18+
<p><strong class="example">Example 3:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> head = []
22+
<strong>Output:</strong> []
23+
</pre>
24+
25+
<p>&nbsp;</p>
26+
<p><strong>Constraints:</strong></p>
27+
28+
<ul>
29+
<li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li>
30+
<li><code>-5000 &lt;= Node.val &lt;= 5000</code></li>
31+
</ul>
32+
33+
<p>&nbsp;</p>
34+
<p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
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+
dummy = ListNode()
9+
current = head
10+
while current:
11+
next_node = current.next
12+
current.next = dummy.next
13+
dummy.next = current
14+
current = next_node
15+
return dummy.next

0 commit comments

Comments
 (0)