From a8075389a238e61ccdb4a65f3cf289af226689bf Mon Sep 17 00:00:00 2001 From: Poonam Raghuvanshi <66264514+Poonam-Raghuvanshi@users.noreply.github.com> Date: Tue, 3 Jan 2023 00:12:46 +0100 Subject: [PATCH] Update RemoveDuplicateLL.java The changes asked in the pull request is added. --- .../Java/linked-lists/RemoveDuplicateLL.java | 41 +++++++++---------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/algorithms/Java/linked-lists/RemoveDuplicateLL.java b/algorithms/Java/linked-lists/RemoveDuplicateLL.java index 73e83ab0..47b4e36e 100644 --- a/algorithms/Java/linked-lists/RemoveDuplicateLL.java +++ b/algorithms/Java/linked-lists/RemoveDuplicateLL.java @@ -1,3 +1,7 @@ +import java.util.Scanner; +/* The RemoveDuplicateLL removes the duplicate elements from a singly linkedlist. In order to remove the duplicates + we first sort the list using the merge sort. The time Complexity for the merge sort is O(n*log n) and + space complexity is O(log n); from the sorted list to remove the duplicate elements the time complexity is O(n). */ public class RemoveDuplicateLL { private Node head = null; class Node { @@ -19,14 +23,13 @@ public class RemoveDuplicateLL { } - /* Sort the list using merge sort it O(n logn)*/ + /* To sort remove the duplicates from the linkedlist it would be better to sort it in O(n logn)*/ Node sortedMerge(Node first, Node second) { Node result; if (first == null) return second; if (second == null) return first; - /* Choose the list which contains smaller elements */ if (first.data <= second.data) { result = first; @@ -66,12 +69,11 @@ public class RemoveDuplicateLL { return slow; } - /* To sort remove the duplicates in O(n)*/ - public Node removeDuplicates(Node head) { + /* To remove the duplicates in O(n)*/ + public Node removeDuplicates() { if(head == null) { return null; } - Node ptr = head; while (ptr.next != null) { if(ptr.data == ptr.next.data) { @@ -89,7 +91,7 @@ public class RemoveDuplicateLL { if(head == null) return; System.out.print("[ "); while(pointer != null) { - System.out.print(pointer.data + " "); + System.out.print(" "+pointer.data + " "); pointer = pointer.next; } System.out.println("]"); @@ -97,30 +99,25 @@ public class RemoveDuplicateLL { public static void main(String [] args) { RemoveDuplicateLL list = new RemoveDuplicateLL(); - list.addNode(9); - list.addNode(2); - list.addNode(7); - list.addNode(1); - list.addNode(8); - list.addNode(3); - list.addNode(7); - list.addNode(5); - list.addNode(4); - list.addNode(8); - list.addNode(1); + System.out.print("Enter the length of list : "); + Scanner sc=new Scanner(System.in); + int length = sc.nextInt(); + for(int i=0; i