链表是线性数据结构,我们给出了一个由整数组成的排序链表。有一些数字可能重复或重复,我们必须将其删除。由于给定的链表已排序,我们可以简单地对其进行迭代,并使用 while 循环可以从中删除重复的节点。我们将通过时间和空间复杂度的讨论来实现适当的代码,以便更好地理解逻辑。
示例given linked list is: 1-> 2 -> 2 -> 3 -> 4 -> 4 -> 4 -> 5 -> 5 -> 5-> 6-> nulloutput: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
说明 - 给定的链表是排序的,这使得很容易找到重复的元素,如果它们等于以前的值,我们可以通过跳过来删除它们。
让我们看看代码的实现方式
方法我们将按照以下步骤来解决问题 -
首先,我们将创建一个类来为链表的节点提供结构。
其次,我们将创建打印链表并向现有链表添加新节点的函数。
我们将创建一个函数来传递要从中删除重复元素的链表的头,它将返回新链表的头。
首先,我们将检查链表是否为空或者其大小是否等于 1。在这些情况下,我们将按原样返回头部。
我们将创建两个变量,一个指示头部,另一个指示头部的下一个节点。
如果当前节点和下一个节点的值相等,那么我们会将下一个节点移动到下一个节点,并更新当前节点的下一个节点的地址。
否则,我们将移动到下一个节点并将下一个节点移动到其下一个节点。
最后我们将返回头部并打印其中存在的值。
示例让我们在代码中实现给定的步骤以便更好地理解
// class to provide structure to linked list nodeclass node{ constructor(val){ this.value = val this.next = null }}// function to print the linked listfunction 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 listvar head = new node(1)var tail = headtail = 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 程序的详细内容。
