Table of Contents
Example
method
Time and space complexity
in conclusion
Home Web Front-end JS Tutorial Javascript program to remove duplicates from sorted linked list

Javascript program to remove duplicates from sorted linked list

Sep 15, 2023 pm 11:41 PM

用于从排序链接列表中删除重复项的 Javascript 程序

The linked list is a linear data structure. We are given a sorted linked list composed of integers. There are some numbers that may be repeated or repeated and we have to remove them. Since the given linked list is sorted, we can simply iterate over it and using a while loop we can remove duplicate nodes from it. We will implement appropriate code through discussion of time and space complexity to better understand the logic.

Example

Given linked list is: 1-> 2 -> 2 -> 3 -> 4 -> 4 -> 4 -> 5 -> 5 -> 5-> 6-> null
Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
Copy after login

Instructions - The given linked list is sorted which makes it easy to find the duplicate elements and we can remove them by skipping if they are equal to the previous value.

Let’s see how the code is implemented

method

We will follow the steps below to resolve the issue -

  • First, we will create a class to provide structure for the nodes of the linked list.

  • Secondly, we will create functions that print the linked list and add new nodes to the existing linked list.

  • We will create a function to pass the head of the linked list from which duplicate elements are to be removed and it will return the head of the new linked list.

  • First, we will check if the linked list is empty or if its size is equal to 1. In these cases we return the head as is.

  • We will create two variables, one indicating the head and the other indicating the next node of the head.

  • If the values ​​of the current node and the next node are equal, then we will move the next node to the next node and update the address of the next node of the current node.

  • Otherwise, we move to the next node and move the next node to its next node.

  • Finally we will return the header and print the value present in it.

Example

Let us implement the given steps in code for better understanding

// class to provide structure to linked list node
class Node{
   constructor(val){
      this.value = val
      this.next = null
   }
}
// function to print the linked list
function print(head){
   var temp = head;
   if(head == null){
      console.log("The given linked list is empty");
   } else {
      var ans = ""
      while(temp.next != null){
         ans += temp.value;
         ans += " -> "
         temp = temp.next
      }
      ans += temp.value
      ans += " -> null"
   }
   console.log(ans)
}
// function to add data in linked list 
function add(data, head, tail){
   var new_node = new Node(data);
   if(head == null){
      head = new_node
      return new_node
   } else {
      tail.next = new_node;
      return new_node
   }
}
// function to remove the duplicate numbers 
function removeDupli(head){
   // if linked list is empty 
   if(head == null){
      return head;
   }
   // if linked list is of size one 
   if(head.next == null){
      return head;
   }
   var temp = head
   var next = head.next
   while(next != null){
      if(temp.value == next.value){
         next = next.next;
         temp.next = next;
      } else {
         next = next.next;
         temp = temp.next;
      }
   }
   return head;
}
// defining linked list
var head  = new Node(1)
var tail  = head
tail = add(2,head, tail)
tail = add(2,head, tail)
tail = add(3,head, tail)
tail = add(4,head, tail)
tail = add(4,head, tail)
tail = add(4,head, tail)
tail = add(5,head, tail)
tail = add(5,head, tail)
tail = add(5,head, tail)
tail = add(6,head, tail)
console.log("The given linked list is: ")
print(head)
// calling function to remove duplicate elements 
head = removeDupli(head)
console.log("The Linked list after removal of duplicate integers is: ")
print(head)
Copy after login

Time and space complexity

The time complexity of the above code is O(N), where N is the total number of nodes in the given linked list. The time complexity is linear because we only traverse the linked list once.

The space complexity of the above code is O(1) because we are not using any extra space.

in conclusion

In this tutorial, we implemented a JavaScript program to remove duplicate elements from a given sorted linked list. Since the linked list is sorted, all duplicate elements are adjacent to each other and can be easily removed by traversing it. The time complexity of the program we implemented is O(N) and the space complexity is O(1).

The above is the detailed content of Javascript program to remove duplicates from sorted linked list. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles