Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Sogrey opened this issue Feb 22, 2020 · 0 comments
Labels
Projects

Comments

@Sogrey
Copy link
Owner

Sogrey commented Feb 22, 2020

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

例如,链表1->2->3->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(5)
node1 = LinkedNode(5)
header.next = node1
node2 = LinkedNode(10)
node1.next = node2
node3 = LinkedNode(4)
node2.next = node3

def printLinked(header):
    p = header
    while p:
        print(p.val)
        p = p.next
header = deleteDuplication(header)
printLinked(header)
@Sogrey Sogrey added the 算法 label Feb 22, 2020
@Sogrey Sogrey added this to 算法 in Python QAs Feb 22, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Development

No branches or pull requests

1 participant