Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2:

Input: 1->1->1->2->3 Output: 2->3

My code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head==None:
            return head
        if head.next==None:
            return head
        origin_head=head
        count=0
        value=head.val
        pre_head=head
        now_head=head
        while head!=None and head.next!=None:
            if head.val==head.next.val:
                while head.next!=None and head.val==head.next.val:
                    head=head.next
                if head.val==origin_head.val:
                    origin_head=head.next
                    if origin_head==None:
                        return None
                pre_head.next=head.next
                head=head.next
                continue
            pre_head=head
            head=head.next
        
        return origin_head
              

Solution: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/