In: Computer Science
I need to implement a method that removes any duplicate items in a list and returns the new values
private static linkedlist removeDuplicates(linkedlist
list)
{
return list;
}
Solution:
public class
removeDuplicates
{
static
class
element
{
int
val;
element
next;
public
element(
int
val)
{
this
.val
= val;
}
}
/* Function to remove
duplicates from a
unsorted linked list */
static
void
removeDuplicate(element
head)
{
//
Hash to store seen values
HashSet<Integer>
hs =
new
HashSet<>();
//Pick
elements one by one
element
current = head;
element
prev =
null
;
while
(current !=
null
)
{
int
curval = current.val;
// If current value is seen before
if
(hs.contains(curval)) {
prev.next
= current.next;
}
else
{
hs.add(curval);
prev
= current;
}
current
= current.next;
}
}
/* Function to print
elements in a given linked list */
static
void
printList(element head)
{
while
(head !=
null
)
{
System.out.print(head.val
+
" "
);
head
= head.next;
}
}
public
static
void
main(String[]
args)
{
element
start =
new
element(50
);
start.next
=
new
element(5
2
);
start.next.next
=
new
element(5
1
);
start.next.next.next
=
new
element(5
2
);
start.next.next.next.next
=
new
element(51
);
start.next.next.next.next.next
=
new
element(5
1
);
start.next.next.next.next.next.next
=
new
element(5
0
);
System.out.println(
"Linked
list before removing duplicates :"
);
printList(start);
removeDuplicate(start);
System.out.println(
"\nLinked
list after removing duplicates :"
);
printList(start);
}
}