问题描述:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
方法1:(超时)
1 class Solution(object): 2 def deleteDuplicates(self, head): 3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 8 p = head 9 if p == None or p.next == None: 10 return head 11 while p.next != None: 12 q = p.next 13 if p.val == q.val: 14 q = q.next 15 else: 16 p.next = q 17 p = q 18 return head
方法2:
1 class Solution(object): 2 def deleteDuplicates(self, head): 3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 8 p = head 9 if p == None or p.next == None: 10 return head 11 while p.next != None: 12 q = p.next 13 if p.val == q.val: 14 p.next = q.next 15 else: 16 p = p.next 17 return head
同上:
1 class Solution(object): 2 def deleteDuplicates(self, head): 3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 #此为不带头结点的链表 8 if head is None:#链表为空 9 return head 10 cur=head 11 while cur.next:#下一节点不为空 12 if cur.val==cur.next.val:#第一次判断,头元素与头元素下一节点的值是否相等。。。 13 cur.next=cur.next.next 14 else: 15 cur=cur.next 16 return head
方法2:
1 class Solution(object): 2 def deleteDuplicates(self, head): 3 """ 4 :type head: ListNode 5 :rtype: ListNode 6 """ 7 a=[] 8 l=head 9 while l: 10 if l.val in a: 11 p.next=l.next 12 else: 13 a.append(l.val) 14 p=l 15 l=l.next 16 return head
2018-07-25 13:08:38