Write a method zip that accepts twolinked lists of integers (with header nodes)
ID: 3616637 • Letter: W
Question
Write a method zip that accepts twolinked lists of integers (with header nodes) and interleaves thetwo lists, e.g., if you give it the two lists 4, 6, 7, 2 and 2, 8,5, 1 it returns the list 4,2,6,8,7,5,2,1. Your method should workon lists of any length (including empty lists).I need help writing this method so I can continue with therest of my program. I can't figure out how to do this and amgetting confused by linked lists after getting used to arrays.PLEASE help! I will rate the first person to help me with a workingmethod lifesaver!
thanks!
I need help writing this method so I can continue with therest of my program. I can't figure out how to do this and amgetting confused by linked lists after getting used to arrays.PLEASE help! I will rate the first person to help me with a workingmethod lifesaver!
thanks!
Explanation / Answer
public static LinkedList<Integer> zip(LinkedList<Integer> list1, LinkedList<Integer>list2){ LinkedList<Integer> result = newLinkedList<Integer>();//create empty linked list
if (list1.isEmpty() && list2.isEmpty()){ return result; }/*if*/ else if (list1.isEmpty() && !list2.isEmpty()){ return list2; }/*if*/ else if (!list1.isEmpty() && list2.isEmpty()){ return list2; }/*if*/
boolean list1waslast = false; while (!list1.isEmpty() && !list2.isEmpty()){//only goas long as interleave is needed int temp;
if (!list1waslast) temp = list1.removeFirst(); else temp = list2.removeFirst(); result.addLast(temp); list1waslast = !list1waslast; }/*while*/
if (!list1.isEmpty())//if list1 still has stuff while (!list1.isEmpty()) result.addLast(list1.removeFirst()); else if (!list2.isEmpty())//if list2 still has stuff while (!list2.isEmpty()) result.addLast(list2.removeFirst());
return result; }/*function*/
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.