leetcode83 python remove duplicate elements in sorted linked list

Given a sorted linked list, remove all duplicate elements such that each element occurs only once.

Example 1:

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

Example 2:

Input: 1->1->2->3->3
 Output: 1->2->3
python code
Given a sorted linked list, remove all duplicate elements such that each element occurs 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):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #This is a linked list without a head node
        if head is None: #The linked list is empty
            return head
        cur=head
        while cur.next:#The next node is not empty
            if cur.val==cur.next.val:#First judgment, whether the value of the head element and the next node of the head element are equal. . .
                cur.next=cur.next.next
            else:
                cur=cur.next
        return head
        




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325729372&siteId=291194637