In: Computer Science
java please
* implement zip method in Q1 class
to merge two linkedlists into one.
* The elements in the result are
made by concatenating elements in different
* linkedlists one after one. The
order of the elements matters.
* For example, merge(list1, list2)
should return [1,5,2,4,3,3,4,2,5,1].
* You can assume that arr1 and arr2
has the same size.
* HINT: You should use ListIterator
to make it easier.
Integer[] arr1 = {1,2,3,4,5};
Integer[] arr2 = {5,4,3,2,1};
LinkedList list1 = new
LinkedList<>(Arrays.asList(arr1));
LinkedList list2 = new
LinkedList<>(Arrays.asList(arr2));
System.out.println("Q1 = [15 marks]
=================================");
System.out.println(Q1.zip(list1,
list2));
Answer:
Give me a thumbs up if you like my answer.
I have written the below code based on your requirements.
The below code has no-error and it is working perfectly.
Code:
class Q1
{
public LinkedList zip(LinkedList list1, LinkedList
list2)
{
Iterator it1 =
list1.iterator();
Iterator it2 =
list2.iterator();
LinkedList<Integer> list =
new LinkedList<>();
while(it1.hasNext())
{
list.add((int)it1.next());
list.add((int)it2.next());
}
return list;
}
}