[剑指offer] 删除链表中的重复节点

题目内容

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

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


题目思路

首先我们需要找到哪些是重复的节点,因而需要遍历一下链表。然后在链表内部进行删除。值得注意的是,如果要删除一个节点,我们最好在当前节点的next节点进行定位,不然需要重新get一个pre指针。


程序代码

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        cnt=[]
        if not pHead:
            return pHead
        p=pHead
        while p:
            cnt.append(p.val)
            p=p.next
        cnt2=[]
        for i in cnt:
            if cnt.count(i)==1:
                cnt2.append(i)
        res=ListNode(0)
        tmp=res
        for i in cnt2:
            tmp.next=ListNode(i)
            tmp=tmp.next
        return res.next
           

猜你喜欢

转载自blog.csdn.net/u010929628/article/details/92782244