删除链表中重复的结点

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

python solution:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def deleteDuplication(self, pHead):
        pre = ListNode(0)
        pre.next = pHead
        work = pre
        if not pHead or not pHead.next:
            return pHead
        while pHead.next:
            if pHead.val!=pHead.next.val:
                work = work.next
                pHead = pHead.next
            else:
                while pHead.next.next and pHead.next.val==pHead.next.next.val:
                    pHead = pHead.next
                if pHead.next.next:
                    work.next = pHead.next.next
                    pHead = pHead.next.next
                else:
                    work.next = None
                    break
        return pre.next
上一篇:C语言反转单向链表的代码


下一篇:4-18 易错点 链表的创建和添加