题目描述
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
**
输入:head = [1,1,2]
输出:[1,2]
**
方法一:前后指针
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def delete(head):
if head is None:
return head
left=head
right=head.next
while right is not None:
if left.val==right.val:
left.next=right.next #删除重复节点
else:
left=right
right=right.next
return head
方法二:遍历链表
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def delete(head):
current = head
while current and current .next:
if current .val==current .next.val:
current .next=current .next.next #删除重复节点
else:
current =current .next
return head