每日一练python29

题目:(删除排序链表中的元素)存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。返回同样按升序排列的结果链表。

示例 1:

输入:head = [1,1,2] 输出:[1,2]
示例 2:

输入:head = [1,1,2,3,3] 输出:[1,2,3]

提示:

链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100 题目数据保证链表已经按升序排列

程序说明:
1、先固定一个节点pre,然后遍历后面的节点cur,若当cur的值与pre的值相等时,删除cur,保留此时的pre。接着cur与pre继续向后移动,继续遍历,判断两节点的值是否相等。(具体如图)
在这里插入图片描述

全部代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if not head: 
            return None
        pre = head
        cur = head.next
        while cur:
            if cur.val == pre.val:
                pre.next = cur.next
            else:
                pre = cur
            cur = cur.next
        return head

题目来源:力扣(LeetCode)

猜你喜欢

转载自blog.csdn.net/qq_52669357/article/details/121770194