方法一:列表囤不重复的值 然后构建新的链表返回,题意没有说要在原链表修改,所以可行
class Solution: def deleteDuplication(self, pHead): # write code here if not pHead: return None a_list = [] while pHead: a_list.append(pHead.val) pHead = pHead.next new_list = [i for i in a_list if a_list.count(i)==1] if new_list: root = pHead = ListNode(new_list[0]) for i in range(1,len(new_list)): pHead.next = ListNode(new_list[i]) pHead = pHead.next return root else: return None
方法二:递归
思路,指针指向当前节点,如果当前节点不为重复值,则当前节点.next = self.deleteDuplication(下一个节点),如果当前节点是重复的,则往下找到一个不重复的节点,return self.deleteDuplication(与当前节点不重复的节点)
链接:https://www.nowcoder.com/questionTerminal/fc533c45b73a41b0b44ccba763f866ef?answerType=1&f=discussion 来源:牛客网 # -*- coding:utf-8 -*- # class ListNode: # def __init__(self, x): # self.val = x确定 # self.next = None class Solution: def deleteDuplication(self, pHead): # write code here if not pHead or not pHead.next:#如果链表为空或只有一个元素,直接返回 return pHead if pHead.val==pHead.next.val:#如果当前结点与下一结点重复,继续查找是否还有重复的 p=pHead.next.next while p and p.val==pHead.val:#如果p结点不为空且其值与当前重复的结点(pHead)相等 p=p.next#p继续往后移位查找,直到没有重复的 return self.deleteDuplication(p)#递归调用函数对头结点为p的链表进行处理 #如果当前结点与下一结点不重复,递归调用函数对头结点为pHead.next的链表进行处理 pHead.next=self.deleteDuplication(pHead.next) return pHead