题解 | #删除链表中重复的结点#

删除链表中重复的结点

https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead ListNode类 
# @return ListNode类
#
class Solution:
    def deleteDuplication(self , pHead: ListNode) -> ListNode:
        # write code here
        if not pHead:
            return None
        hash_table = dict()
        cur = pHead
        while cur:
            if cur.val in hash_table.keys():
                hash_table[cur.val] = True
            else:
                hash_table[cur.val] = False
            cur = cur.next
        cur = pHead
        pre = None
        while cur:
            if hash_table[cur.val] == True:
                cur = cur.next
                if pre is not None:
                    pre.next = cur
                else:
                    # pre为空只能是第一个元素重复 所以pHead = pre == None
                    pHead = pre
            else:
                # 此时 哈希表情况为False 所以不是重复节点 需要重置表头
                # 防止 1 1 1 1 1 1 7情况
                if pre is None:
                    pre = cur
                    cur = cur.next
                    pHead = pre
                # 普通的连表情况
                else:
                    pre = cur 
                    cur = cur.next
        return pHead

全部评论

相关推荐

04-06 11:24
已编辑
太原学院 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务