First, understand the topic

83. Remove duplicate elements from sorted lists

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.

Example:

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

Ii. Solution analysis

(1) How to solve the problem

  • Because the list is ordered, the repeating elements must be adjacent;
  • Iterate through the list and delete the next element if the current element is found to have the same value as the next element.

(2) Steps to solve the problem

  • Iterate through the linked list, if the current element and the next element value is the same, delete the next element value;
  • After traversal, return to the head of the original list.

Three, code implementation

Based on the above solution, we will use JS to implement this problem. The specific implementation code is as follows:

/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */
/ * * *@param {ListNode} head
 * @return {ListNode}* /
 var deleteDuplicates = function(head) {
    // 1. Define a p pointer to the header
    let p = head;
    // 2. Check whether the current node and the next node of the current node exist
    while(p && p.next){
        // 2.1 The value of the current node is the same as that of the next node
        if(p.val === p.next.val){
            // 2.1.1 Set the next pointer of the current node to the pointer of the next node, thus deleting the next element
            p.next = p.next.next;
        }
        // 2.2 If the values are different, the current node will continue to point to the next node for the next round of comparison
        else{ p = p.next; }}// 3. Return the contents of the p pointer
    return head;
};
Copy the code

Delete duplicate elements from a sorted list. Delete duplicate elements from a sorted list.

We’ll see you next time at 👋👋👋