In: Computer Science
In Java, write the method public static void insertUnique(List l, T e), user of the ADT List. The method takes a list l and an element e and inserts the element at the end of the list only if it is not already there. Example 0.2. If l : A → B → C, then after calling insertUnique(l, "C"), the list does not change. Calling insertUnique(l, "D") will make l be : A → B → C → D.
import java.util.*;
public class linklist {
public static void insertUnique(LinkedList<String> l,String e)
{
if(l.contains(e))
System.out.println(l);
else {
l.add(e);
System.out.println(l);
}
}
public static void main(String args[])
{
// Creating object of the
// class linked list
LinkedList<String> l
= new LinkedList<String>();
// Adding elements to the linked list
l.add("A");
l.add("B");
l.add("C");
System.out.println(l);
insertUnique(l,"D");
}
}
Explanation of Code
1. First we have imported the utils package which contain a in-build linked list class which we will be using to make the linked list.
import java.util.*;
2. Now in the public static void main() we have created an object of linkedlist class which is 'l'.
LinkedList<String> l = new LinkedList<String>();
3. Then we have used the add() which is available in the linkedlist class which allows us to insert values in the linked list. Then we have printed the list on othe output screen using println.
l.add("A"); l.add("B"); l.add("C"); System.out.println(l);
4. Then called the insertUnique() method .
insertUnique(l,"D");
5. Now let's see the insertUnique() method. In this method we have passed the linked list obejct 'l' and a String type object 'e' which is the value to be inserted in the list.
public static void insertUnique(LinkedList<String> l,String e)
6. Now in the body of insertUnique() we have checked if the String 'e' is already present in the list or not using the contains() method available in the linkedlist class. We have called the contains() method in if else block. If the contains() method returns true that means the linked list already contains the String 'e' so first if block will be executed and we have printed the list as it is.
if(l.contains(e)) System.out.println(l);
7. If the contains() method returns false then the else block will be executed. In the else block we have used another method available in the linkedlist class which is add(). add() adds a new value ot the linked list at the end. Then we have printed the new list.
else { l.add(e); System.out.println(l); }
OUTPUT