Topic describes

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.

Input: head = [1,2]

//
// 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 the same as the next

//
// 1, iterate through the list and delete the next element if it finds that the current element has the same value as the next element
// 2, after traversal, return to the head of the original list
// 3, VX:mike_fss888

/ * * *@param {ListNode} head
 * @return {ListNode}* /
var deleteDuplicates = function (head) {
  let p = head
  while (p && p.next) { // Make sure the next value has a value
    if (p.val === p.next.val) {
      p.next = p.next.next
    } else {
      p = p.next // The same element is killed}}return head
};

// Time complexity: O(n)
// Space complexity: O(1)

// The title is reprinted from licou official website:
// https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
Copy the code