leetcode笔记--Remove Duplicates from Sorted List II

来源:互联网 发布:java string == equal 编辑:程序博客网 时间:2024/05/01 18:50

题目:难度(Medium)

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.
Tags:Linked List

分析:对于一个已经排好序的链表,将链表中发生重复的元素都删除,只留下原链表中不重复的节点。

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def deleteDuplicates(self, head):        """        :type head: ListNode        :rtype: ListNode        """                #链表为空或只有一个节点,直接返回即可        if head is None or head.next is None:            return head                #如果头节点就是重复值,则直接修改头节点即可         while head and head.next and head.val == head.next.val:            p = head            q = head.next            while q is not None and p.val == q.val:                p = q                q = q.next            #此时p、q的值不相等            if p is not head:                head = q                        #此时重复值不可能再出现在头节点,只可能是形如1->2->2->3->3->3->4->null的链表        if head is not None:            p = head            q = head.next            #flag用来标记是否头重复值            flag = 0            while q is not None:                while q.next is not None and q.val == q.next.val:                    q = q.next                    flag = 1                if flag == 1:                    p.next = q.next                    q = q.next                    flag = 0                else:                    p = q                    q = q.next                return head


0 0
原创粉丝点击