问题描述:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 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 head11 while p.next != None:12 q = p.next13 if p.val == q.val:14 q = q.next15 else:16 p.next = q17 p = q18 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 head11 while p.next != None:12 q = p.next13 if p.val == q.val:14 p.next = q.next15 else:16 p = p.next17 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 head10 cur=head11 while cur.next:#下一节点不为空12 if cur.val==cur.next.val:#第一次判断,头元素与头元素下一节点的值是否相等。。。13 cur.next=cur.next.next14 else:15 cur=cur.next16 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.next12 else:13 a.append(l.val)14 p=l15 l=l.next16 return head
2018-07-25 13:08:38