Skip to content

Commit 7ae2125

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 19.6 MB (82.06%)
1 parent 29f2c94 commit 7ae2125

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<p>Given the <code>head</code> of a linked list and an integer <code>val</code>, remove all the nodes of the linked list that has <code>Node.val == val</code>, and return <em>the new head</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/03/06/removelinked-list.jpg" style="width: 500px; height: 142px;" />
6+
<pre>
7+
<strong>Input:</strong> head = [1,2,6,3,4,5,6], val = 6
8+
<strong>Output:</strong> [1,2,3,4,5]
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> head = [], val = 1
15+
<strong>Output:</strong> []
16+
</pre>
17+
18+
<p><strong class="example">Example 3:</strong></p>
19+
20+
<pre>
21+
<strong>Input:</strong> head = [7,7,7,7], val = 7
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 in the range <code>[0, 10<sup>4</sup>]</code>.</li>
30+
<li><code>1 &lt;= Node.val &lt;= 50</code></li>
31+
<li><code>0 &lt;= val &lt;= 50</code></li>
32+
</ul>
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 removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
8+
if not head:
9+
return None
10+
11+
dummy = ListNode(-1, head)
12+
last = dummy
13+
14+
while last.next:
15+
if last.next.val != val:
16+
last = last.next
17+
else:
18+
last.next = last.next.next
19+
20+
return dummy.next

0 commit comments

Comments
 (0)