题目内容
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
题目思路
首先我们需要找到哪些是重复的节点,因而需要遍历一下链表。然后在链表内部进行删除。值得注意的是,如果要删除一个节点,我们最好在当前节点的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