Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

describe

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1:

Input: head = [1,2] Output: [1,2]Copy the code

Example 2:

Input: head = [1,1,2,3] Output: [1,2,3]Copy the code

Note:

The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
Copy the code

parsing

The list is still sorted. The result is that the list is still sorted. The result is that the list is still sorted.

  • Head from the traversal list
  • If head is empty, return head directly
  • If the head has no next node, it is itself a linked list with no duplicate nodes, and returns the head directly
  • Initialize result result, and assign head
  • In the while loop, when head is true and head. Next is true, if the next node of head is equal to the current node, the current node is directly connected to the next node of the next node, and the process is repeated
  • Finally, return result directly

answer

class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head :return head
        if head and not head.next: return head
        result = head
        while head and head.next:
            if head.val == head.next.val:
                head.next = head.next.next
            else:
                head = head.next
        return result
                        	      
		
Copy the code

The results

Given nodes in the Python online submission List. Node Usage: Given nodes in Python online submissions for Remove Duplicates from the Sorted List.Copy the code

Original link: leetcode.com/problems/re…

Your support is my biggest motivation