Given two nonempty sorted lists , L1 and L2 . (a) Complete a following method in
ID: 3848044 • Letter: G
Question
Given two nonempty sorted lists, L1 and L2.
(a) Complete a following method in Java that prints true if L2 L1, and false otherwise. In your implementation you can use only the basic list operators (next(), hasNext(), and compareTo()).
Remember that L2 L1 if for all x L2, x L1.
public static <AnyType extends Comparable<? super AnyType>>
boolean subset(List<AnyType> L1, List<AnyType> L2)
{
ListIterator iterL1 = L1.listIterator();
ListIterator iterL2 = L2.listIterator();
// get first item in each list
if ( iterL1.hasNext() && iterL2.hasNext() )
{
itemL1 = iterL1.next();
itemL2 = iterL2.next();
}
// YOUR CODE GOES HERE
//
//
//
}
(b) What is the running time complexity of your method?
Explanation / Answer
/*
//This program accepts Object type value and prepares two lists. Then it checks whether elements of L2 are subset //of L1? If yes program returns true else false
*/
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class testList {
public static void main(String[] args) {
boolean ifsubset = false;
List<Object> L1 = new ArrayList<Object>();
L1.add(1);
L1.add("temp");
L1.add(2);
List<Object> L2 = new ArrayList<Object>();
L2.add(1);
L2.add(2);
L2.add("temp");
ifsubset = subset(L1, L2);
System.out.println(ifsubset);
}
public static boolean subset(List<Object> L1, List<Object> L2)
{
ListIterator<Object> iterL1 = L1.listIterator();
ListIterator<Object> iterL2 = L2.listIterator();
Object itemL1=0;
Object itemL2=0;
int arr[] = new int[L2.size()];
boolean subset = false;
int k=0;
// get first item in each list
if ( iterL1.hasNext() && iterL2.hasNext() )
{
for(int i=0;i<L1.size();i++)
{
itemL1 = iterL1.next();
iterL2 = L2.listIterator();
for(int j=0;j<L2.size();j++)
{
if(iterL2.hasNext())
{
itemL2 = iterL2.next();
if(itemL1==itemL2)
{
arr[k]= 1;
k++;
//subset = true;
iterL2 = L2.listIterator();
break;
}
else
{
//subset = false;
continue;
}
}
}
}
}
int sum=0;
for(int i=0;i<arr.length;i++)
{
sum+=arr[i];
}
if (sum==arr.length)
return true;
else
return false;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.