This is the third day of my participation in the August Text Challenge.More challenges in August

Title description:

83. Delete duplicate elements from sorted lists – LeetCode (leetcode-cn.com)

There is a linked list in ascending order. Given the head node of the linked list, remove all duplicate elements so that each element appears only once.

Returns a linked list of results, also in ascending order.

The sample a

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

Example 2

Head = [1,1,2,3,3]Copy the code

Tip:

  • The number of nodes in the linked list is in the range[0, 300] 内
  • -100 <= Node.val <= 100
  • The subject data ensures that the linked list is sorted in ascending order

Thought analysis

A traversal

Since the list is an ascending list, the repeating elements must be contiguous, and we can remove the repeating elements by traversing the list once.

Steps:

  • Define a pointer cur to head
  • Compare the value of the current node with the value of the next node,
    • If they are the same, the cur nodes point to the next node of the cur node, so that the original node of the cur node has no nodes to point to
    • If different, cur moves back one bit to continue the cycle

AC code

class Solution {
    fun deleteDuplicates(head: ListNode?).: ListNode? {
        // dummy head points to head and returns dummy.next. Note: -100 <= node. val <= 100
        val dummy = ListNode(-101)
        dummy.next = head
        var cur: ListNode? = dummy
        
        while(cur? .next ! =null) {
            if(cur? . `val` == cur? .next? . `val`) {
                // Skip the current repeating node so that cur points to the last position of the current repeating elementcur? .next = cur? .next? .next }else {
                // Move to the next position without repeatingcur = cur? .next } }return dummy.next
    }
    
}
Copy the code

conclusion

This is just a simple linked list problem, the loop is easy to think of, and the official solution is the same. There’s another recursion in the comments section, so try it next time.

reference

Delete duplicate elements from sorted list – Delete duplicate elements from sorted list – LeetCode (leetcode-cn.com)

83. Delete duplicate elements from sorted list – Delete duplicate elements from sorted list – LeetCode (leetcode-cn.com)