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

Commit f36617c

Browse files
#82: Remove Duplicates from Sorted List II
1 parent a752096 commit f36617c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎Linkedlist/delete_duplicates_II.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Given the head of a sorted linked list, delete all nodes that have duplicate
2+
# numbers, leaving only distinct numbers from the original list. Return the
3+
# linked list sorted as well.
4+
5+
6+
# Example 1:
7+
# Input: head = [1,2,3,3,4,4,5]
8+
# Output: [1,2,5]
9+
10+
# Example 2:
11+
# Input: head = [1,1,1,2,3]
12+
# Output: [2,3]
13+
14+
15+
# Constraints:
16+
17+
# The number of nodes in the list is in the range [0, 300].
18+
# -100 <= Node.val <= 100
19+
# The list is guaranteed to be sorted in ascending order.
20+
21+
22+
23+
from typing import Optional
24+
# Definition for singly-linked list.
25+
class ListNode:
26+
def __init__(self, val=0, next=None):
27+
self.val = val
28+
self.next = next
29+
class Solution:
30+
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
31+
dummy = ListNode(0, head)
32+
current = head
33+
prev = dummy
34+
while current:
35+
while current.next and current.val == current.next.val:
36+
current = current.next
37+
if prev.next == current:
38+
prev = prev.next
39+
else:
40+
prev.next = current.next
41+
current = current.next
42+
return dummy.next
43+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /