首页  >  文章  >  web前端  >  用于从排序链接列表中删除重复项的 Javascript 程序

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

PHPz
PHPz转载
2023-09-15 23:41:02999浏览

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

链表是线性数据结构,我们给出了一个由整数组成的排序链表。有一些数字可能重复或重复,我们必须将其删除。由于给定的链表已排序,我们可以简单地对其进行迭代,并使用 while 循环可以从中删除重复的节点。我们将通过时间和空间复杂度的讨论来实现适当的代码,以便更好地理解逻辑。

示例

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

说明 - 给定的链表是排序的,这使得很容易找到重复的元素,如果它们等于以前的值,我们可以通过跳过来删除它们。

让我们看看代码的实现方式

方法

我们将按照以下步骤来解决问题 -

  • 首先,我们将创建一个类来为链表的节点提供结构。

  • 其次,我们将创建打印链表并向现有链表添加新节点的函数。

  • 我们将创建一个函数来传递要从中删除重复元素的链表的头,它将返回新链表的头。

  • 首先,我们将检查链表是否为空或者其大小是否等于 1。在这些情况下,我们将按原样返回头部。

  • 我们将创建两个变量,一个指示头部,另一个指示头部的下一个节点。

  • 如果当前节点和下一个节点的值相等,那么我们会将下一个节点移动到下一个节点,并更新当前节点的下一个节点的地址。

  • 否则,我们将移动到下一个节点并将下一个节点移动到其下一个节点。

  • 最后我们将返回头部并打印其中存在的值。

示例

让我们在代码中实现给定的步骤以便更好地理解

// 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)

时间和空间复杂度

上述代码的时间复杂度为 O(N),其中 N 是给定链表中的节点总数。时间复杂度是线性的,因为我们只遍历了链表一次。

上述代码的空间复杂度为 O(1),因为我们没有使用任何额外的空间。

结论

在本教程中,我们实现了一个 JavaScript 程序,用于从给定的排序链表中删除重复元素。由于链表是排序的,因此所有重复元素都彼此相邻,并且可以通过遍历它轻松删除。我们实现的程序时间复杂度为O(N),空间复杂度为O(1)。

以上是用于从排序链接列表中删除重复项的 Javascript 程序的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除