给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
1、
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
ans = head
while head != None:
if head.next != None and head.next.val == head.val:
head.next = head.next.next
else:
head = head.next
return ans
2、
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def append(self,l2:ListNode, data):
if l2.val is None:
l2.val = data
else:
node = l2
while node.next:
node = node.next
node.next = ListNode(data)
def deleteDuplicates(self, head: ListNode):
if head is None:
return head
a = []
l3 = ListNode(None)
while head:
if head.val not in a:
a.append(head.val)
self.append(l3, head.val)
head = head.next
return l3
3、
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
cur = ListNode(0)
cur = head
while (cur != None and cur.next != None):
if cur.next.val == cur.val:
cur.next = cur.next.next
else:
cur = cur.next
return head