*【链表】删除链表中重复的结点

2019-08-14  本文已影响0人  一个想当大佬的菜鸡

搞半天,总报错,细节问题

class Solution:
    def deleteDuplication(self, pHead):
        if pHead == None:
            return pHead
        dummy = ListNode(0)
        dummy.next = pHead
        pre = dummy
        p = pHead
        while p and p.next:
            if p.next.val == p.val:
                val = p.val
                while p and p.val == val:
                    p = p.next
                pre.next = p
            else:
                pre = p
                p = p.next
        return dummy.next

这一版是留下重复的结点,比较简单

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        if pHead == None:
            return pHead
        dummy = ListNode(0)
        dummy.next = pHead
        pre = dummy
        p = pHead
        while p:
            while p.next and p.next.val == p.val:
                p = p.next
            pre.next = p
            pre = p
            p = p.next
        return dummy.next
上一篇下一篇

猜你喜欢

热点阅读