Skip to content

Commit 9d885a2

Browse files
Question 82
1 parent 48a8e95 commit 9d885a2

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

82. Remove Duplicates from Sorted List II.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,43 @@
1313
Output: 2->3
1414
'''
1515

16+
# Definition for singly-linked list.
17+
# class ListNode:
18+
# def __init__(self, val=0, next=None):
19+
# self.val = val
20+
# self.next = next
21+
22+
23+
class Solution:
24+
def deleteDuplicates(self, head: ListNode) -> ListNode:
25+
if head==None or head.next==None:
26+
return head
27+
28+
if head.next.val == head.val:
29+
temp = head
30+
head = head.next
31+
while(head):
32+
if head.val!=temp.val:
33+
if head.next==None:
34+
break
35+
elif head.val!=head.next.val:
36+
break
37+
temp = temp.next
38+
head = head.next
39+
40+
if head==None:
41+
return head
42+
43+
pointer = head
44+
prev = head
45+
temp = head.next
46+
while(temp):
47+
if prev.val!=temp.val:
48+
if temp.next==None or temp.next.val!=temp.val:
49+
pointer.next = temp
50+
pointer = temp
51+
prev = prev.next
52+
temp = temp.next
53+
pointer.next = temp
54+
return head
55+
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'''
2+
Given a sorted linked list, delete all duplicates such that each element appear only once.
3+
4+
Example 1:
5+
6+
Input: 1->1->2
7+
Output: 1->2
8+
Example 2:
9+
10+
Input: 1->1->2->3->3
11+
Output: 1->2->3
12+
'''
13+
14+
# Definition for singly-linked list.
15+
# class ListNode:
16+
# def __init__(self, val=0, next=None):
17+
# self.val = val
18+
# self.next = next
19+
20+
21+
class Solution:
22+
def deleteDuplicates(self, head: ListNode) -> ListNode:
23+
if head==None or head.next==None:
24+
return head
25+
pre = head
26+
cur = head.next
27+
while(cur):
28+
if pre.val==cur.val:
29+
pre.next = cur.next
30+
cur = cur.next
31+
else:
32+
pre = pre.next
33+
cur = cur.next
34+
return head

0 commit comments

Comments
 (0)