Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How leetcode removes repeating elements from a sorted linked list

Shulou Source: shulou.com Published: 2022-06-01 01:05:23 09月25日 Update

This article mainly introduces how to delete the repeated elements in the sorted list by leetcode. It is very detailed and has a certain reference value. Friends who are interested must read it!

Topic link

Https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/

Topic description

Given a sorted linked list, delete all duplicate elements so that each element appears only once.

Example 1:

Input: 1-> 1-> 2 output: 1-> 2

Example 2:

Input: 1-> 1-> 2-> 3-> 3 output: 1-> 2-> 3 solution

Tags: linked list

Specifies that the cur pointer points to the header head

When the existence of cur and cur.next is the condition for the end of the loop, when one of them does not exist, it is not necessary to repeat the linked list.

When cur.val and cur.next.val are equal, it means that it needs to be de-duplicated, then point the next pointer of cur to the next one, so that the effect of de-repetition can be achieved.

If not, the cur moves to the next position to continue the loop.

Time complexity: O (n)

Code

Java version

/ * Definition for singly-linked list. * public class ListNode {* int val; * ListNode next; * ListNode (int x) {val = x;} *} * / class Solution {public ListNode deleteDuplicates (ListNode head) {ListNode cur = head; while (cur! = null & & cur.next! = null) {if (cur.val = = cur.next.val) {cur.next = cur.next.next } else {cur = cur.next;}} return head;}}

JavaScript version

/ * Definition for singly-linked list. * function ListNode (val) {* this.val = val; * this.next = null; *} * / / * @ param {ListNode} head * @ return {ListNode} * / var deleteDuplicates = function (head) {var cur = head; while (cur & cur.next) {if (cur.val = = cur.next.val) {cur.next = cur.next.next } else {cur = cur.next;}} return head;}; drawing interpretation

The above is all the content of the article "how to remove repeating elements from the sorted list by leetcode". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Elements sorting content pointing pointers versions examples articles topics loops input output complexity necessity code value location interest complexity header Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL NVidia Shulou Information Shulou Tech Info Huawei