1.问题描述:
给定一个排序链表,删除所有重复的元素每个元素只留下一个。
2.样例:
给出 1->1->2->null
,返回 1->2->null
给出 1->1->2->3->3->null
,返回 1->2->3->null
3.代码:
因为给定的已知是排序链表,使用双指针,依次判断
如果遇到相同的元素,则把利用链表删除结点的方法,删除元素即可
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: head: head is the head of the linked list
@return: head of linked list
"""
def deleteDuplicates(self, head):
# write your code here
if head is None:
return head
pre=head
cur=head.next
while cur:
if pre.val<cur.val:
pre=cur
cur=cur.next
else:
pre.next=cur.next
cur=cur.next
return head