Remove Duplicates from Sorted List

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

# Solution

Double Pointer / Fast And Slow Pointer

# Code

• submit code
``````# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Base Condition
if head == None:
return head

fast = head
slow = head

while fast != None:
if fast.val != slow.val:
# important
slow = slow.next
slow.val = fast.val
fast = fast.next

slow.next = None
return head
``````
• full code to understand
``````class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def deleteDuplicates(self, head):
listN = ListNode(head[0])
tmp = listN
# Create ListNode From head list
for m in range(1,head.__len__()):
listN.next = ListNode(head[m])
listN = listN.next

fast = tmp
slow = tmp

while fast != None:
if fast.val != slow.val:
slow = slow.next
slow.val = fast.val
fast = fast.next

slow.next = None

return tmp

head = [1,1,2,3,4,5,5]
# head = [1,1,2,2]

S = Solution()
ret = S.deleteDuplicates(head)
while ret != None:
print(ret.val)
ret = ret.next
``````

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2022/03/15/remove-duplicates-from-sorted-list/``

## 优惠码

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安