LeetCode ❀ 83. Remove duplicate elements in sorted linked list / python

topic:

Given the head of a sorted linked list  head ,  remove all duplicate elements so that each element appears only once  . Returns  a sorted linked list  .

Example 1:

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

 Example 2:

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

answer:

class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return head
        # 判断是否为空,如果是空的,则直接return

        cur = head
        # 创建一个新指针cur来使用

        while cur.next:
        # 当这个列表还没被遍历完时
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            # 如果当前val和下一个val相同,则把next指针指向下下个
            elif cur.val != cur.next.val:
                cur = cur.next
            # 如果当前val和下一个val不同,则把当前指针指向下一个Node
        return head

Guess you like

Origin blog.csdn.net/qq_42395917/article/details/126631280