Nuggets team number online, help you Offer impromptu! Click on theCheck the details

1. Title Description

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.Copy the code

Eg1: input, output head =,1,2 [1] : [1, 2] eg2: input: head = output,1,2,3,3 [1] : [1, 2, 3]Copy the code

Second, train of thought analysis

2. Traverse the linked list to determine whether the current element and the next element are the same, and delete the next element if they areCopy the code

Three, the solution code

/** * 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) {
    let p1 = head
    while (p1 && p1.next) {
        if (p1.val === p1.next.val) {
            p1.next = p1.next.next
        } else {
            p1 = p1.next  // Move pointer when you don't want to wait}}return head
};
 

Copy the code
Time complexity: O(n) Space complexity: O(1)Copy the code

Four,

  • If the list is arranged in ascending order, the repeating elements must be adjacent.
  • Practice every day and keep learning