LeetCode 82.删除排序链表中的重复元素II

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例 2:

输入: 1->1->1->2->3
输出: 2->3

写得太渣渣

# 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 or head.next==None:#如果是空链表,或者只有一个节点的链表,直接返回
            return head
        
        #先处理头部,让第一个数字不是重复的
        while head!=None and head.next!=None and head.val==head.next.val:
            num=head.val
            while head!=None and head.val==num:
                head=head.next
        
        if head==None or head.next==None or head.next.next==None:#如果变成空链表,或者只有一个、两个节点的链表,直接返回
            return head
        
        ptr=head.next#指向当前数字
        preptr=head#指向上一个不同的数字

        while ptr!=None and ptr.next!=None:
            num=ptr.val
            if ptr.next.val==num:
                while ptr!=None and ptr.val==num:
                    preptr.next=ptr.next
                    ptr=ptr.next
            else:
                preptr=ptr
                ptr=ptr.next
                
        return head           

猜你喜欢

转载自blog.csdn.net/qq_34919415/article/details/85112588