删除链表中重复的结点

删除链表中重复的结点_牛客网

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=11209&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

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

def deleteDuplication(self, pHead):
    # write code here
    if not pHead:
        return pHead
    #为了防止头结点是重复的,定义一个新结点指向头结点
    temp = ListNode(0)
    temp.next = pHead
    pre, nex = temp, pHead
    while nex:
        if nex.next and nex.next.val == nex.val:
            #如果出现了和当前节点相同的值的时候,当前节点前移一位
            while nex.next and nex.next.val == nex.val:
                nex = nex.next
            pre.next = nex.next#只是指向,并没有动pre,相当于删除
            nex = nex.next
        else:
            pre = pre.next
            nex = nex.next
    return temp.next
全部评论
pre 变指向但是不动,牛逼
点赞 回复
分享
发布于 2019-09-29 14:07
那 [4,4,4,4]这种不就错了?返回[4] 应该返回[]吧
点赞 回复
分享
发布于 2019-10-24 15:50
滴滴
校招火热招聘中
官网直投

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务