JZ56:删除链表中重复的结点

题目描述:

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5处理后为1->2->5

解法:

这题必须要设置一个虚拟节点dummy,最后返回dummy.next。因为链表头可能重复,这样就得把头删了。分两种情况,一种是cur.val == beh.val,另一种是cur.val != beh.val,分别讨论就行。

代码:

class Solution:
    def deleteDuplication(self, pHead):
        if not pHead or not pHead.next:
            return pHead
        dummy = ListNode(0)
        pre = dummy
        pre.next = pHead
        cur = pHead
        beh = pHead.next
        while beh:
            rep = 0
            while cur.val == beh.val:
                rep = 1
                beh = beh.next
                if not beh:
                    pre.next = None
                    return dummy.next
            if rep == 1:
                pre.next = beh
                cur = beh
                beh = beh.next
            else:
                pre = cur
                cur = beh
                beh = beh.next
        return dummy.next

你可能感兴趣的:(JZ56:删除链表中重复的结点)