【leetcode】删除排序链表中的重复元素(python实现)

题目:
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

    输入: 1->1->2
    输出: 1->2

示例二:

 输入: 1->1->2->3->3
 输出: 1->2->3

因为给出的是个有序列表,所以我们可以这么想:

对链表进行遍历,当链节值与下一个链节值是相等的,那么就说明重复了,就让当前链节的下个链节指向下下个链节,这样就相当于过滤掉了相同值得链节

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        while cur and cur.next:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        
        return head

猜你喜欢

转载自blog.csdn.net/qq_43538596/article/details/88957875
今日推荐