Remove Duplicates from Sorted List (python)

对于Remove Duplicates from Sorted List这个题有两种:第一种是将重复的元素只保留一个,多余重复的去掉;第二种是重复的节点都去掉。

第一种:

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->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:
        if not head or not head.next:
            return head
        cur = head
       
        while cur:
            before = cur
            while cur and cur.next and cur.val== cur.next.val:
                
                cur = cur.next
                
            before.next = cur.next
            cur = cur.next
        return head


第二种:

题目描述

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

 

解题思路:

这种情况下稍微比上面第一种情况复杂一点,不能直接将每次遍历的当前节点记录成前一个节点,然后当前节点再往后移动

由于会出现开头节点就是重复节点会被删掉,导致原链表的头节点改变。一般涉及到链表头节点会改变的题目,都会先预设一个虚拟头节点(new_head),头节点的下一个元素永远指向链表的头节点,返回时只需返回虚拟节点的下一个元素即可(new_head.next)

要完全删除链表中的重复元素,需要记录当前节点的前一个节点,当遇到重复元素后就不断跳过重复元素,直到遇到和当前值不重复的节点,此时需要将记录的前节点的以下一个元素指向遇到的和当前值不重复的节点。由于此时不能保证遇到的和当前值不重复的节点之后是不是也是含有有重复值的节点,因此不能将记录的前节点设置成当前元素,只有当遍历时的节点和下一个节点不重复时(而不是判断重复元素循环跳出遇到的不同节点),才把记录的前节点设置成当前节点。

代码如下:

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:

        if not head or not head.next:
            return head

        before = new_head = ListNode(-1)
        new_head.next = head
        cur = head
        
        while cur and cur.next:
            #跳过重复节点
            if cur.val == cur.next.val:
                while cur.next and cur.val == cur.next.val:
                    cur = cur.next
                before.next = cur.next 
            #只有当前节点和下一个节点不相等的时候before节点才会移动
            else:
                before = cur
                
            cur = cur.next
        
        return new_head.next

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值