给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
node=head
while node and node.next:
if node.val==node.next.val:
node.next=node.next.next
else:
node=node.next
return head
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy_head = ListNode(None)
dummy_head.next = head
pre = dummy_head
cur = head
while cur:
if pre and cur.val == pre.val:
pre.next = cur.next
cur.next = None
cur = pre.next
continue
pre = cur
cur = cur.next
return dummy_head.next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
child = self.deleteDuplicates(head.next)
if child and head.val == child.val:
head.next = child.next
child.next = None
return head
来源:力扣(LeetCode)
网友评论