题目描述:
题解一:
1.将链表中不重复的数值保存在list nums中。
2.对nums中的元素构造链表。
class Solution(object): def deleteDuplicates(self, head): if head==None: return head nums = [] while head!=None: if head.val not in nums: nums.append(head.val) head = head.next node1 = ListNode(val=nums[-1]) if len(nums)==1: return node1 for i in range(len(nums)-2,-1,-1): node = ListNode(val=nums[i],next=node1) node1 = node return node
题解二:
class Solution(object): def deleteDuplicates(self, head): h = ListNode(0) h.next = head if head==None or head.next==None: return head pre = h cur = head while cur: while cur.next and cur.val == cur.next.val: cur = cur.next pre.next = cur pre = pre.next cur = cur.next return h.next
题解三:递归
1.终止条件:输入head为空或者只有一个节点。
2.返回值:去重之后的head节点。
3.当前递归需要完成的操作:
当前将链表看作两个部分:head节点 和已经进行了去重的head.next
如果head.val=head.next.val,则返回head.next,否则返回head
class Solution(object): def deleteDuplicates(self, head): if head==None or head.next==None: return head head.next = self.deleteDuplicates(head.next) if head.val==head.next.val: return head.next return head