Leetcode brushing record-83. Delete duplicate elements in the sorted linked list

Insert picture description here
The idea is to set two pointers,
where one this points to the last number that appeared first (initialized to None) and the
other cur points to the currently investigated number.
At the beginning, this is None, and cur starts from the first element,
when this is None , We make this point to the element pointed to by cur.
Then, if the value of the element pointed to by cur is equal to the value of the element pointed to by this, we let the next of this refer to
the next of cur. this is cur

# 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:
        this = None#存放上一个要保留的元素
        cur = head
        while cur != None:
            if this == None:
                this = cur
            else:#有
                if cur.val != this.val:
                    this.next = cur
                    this = cur
                elif cur.val == this.val:
                    this.next = cur.next
            cur = cur.next
        return head
Published 59 original articles · Liked 14 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/weixin_41545780/article/details/105481253