十年老IT知识分享 – 87 – 删除链表中重复的节点

在一个链表中,存在重复的节点,请删除该链表中重复的节点,重复的节点只保留一个,最后返回链表头指针

例如:链表1->2->3->4->4->5, 处理后为 1->2->3->4->5

class LinkedNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        
def deleteDuplication(pHead):
    nodeValues = {}
    newHead = LinkedNode(pHead.val)
    nodeValues[pHead.val] = pHead.val
    
    curNode = newHead
    while pHead.next:
        pHead = pHead.next
        if nodeValues.get(pHead.val) == None:
            curNode.next = LinkedNode(pHead.val)
            curNode = curNode.next
            nodeValues[pHead.val] = pHead.val
    return newHead

header = LinkedNode(1)
node1 = LinkedNode(1)
header.next = node1
node2 = LinkedNode(2)
node1.next = node2

def printLinked(header):
    p = header
    while p:
        print(p.val)
        p = p.next
        
header = deleteDuplication(header)
printLinked(header)

1

2

正文完