Write a method called transferFrom that accepts a second linked list as paramete
ID: 644271 • Letter: W
Question
Write a method called transferFrom that accepts a second linked list as parameter and that moves values from the second list to this list. You are to attach the second list's elements to the end of this list. You are also to empty the second list. For example, suppose two lists called list1 and list2 store [8,17,2,4] and [1,2,3], respectively. The call of list1.transferFrom( list 2); should change list1 to [8,17,2,4,1,2,3] and list2 to an empty list,[]. The order of the arguments matters; list2.transferFrom (list1); should change list1 to an empty list, [], and list2 to [1,2,3,8,17,2,4]. Either of the two list could be empty, but you can assume that nether list is null. You are not to create any new nodes. Your method should simply change links of the list to join them together. Write a method called transferFrom that accepts a second linked list as parameter and that moves values from the second list to this list. You are to attach the second list's elements to the end of this list. You are also to empty the second list. For example, suppose two lists called list1 and list2 store [8,17,2,4] and [1,2,3], respectively. The call of list1.transferFrom( list 2); should change list1 to [8,17,2,4,1,2,3] and list2 to an empty list,[]. The order of the arguments matters; list2.transferFrom (list1); should change list1 to an empty list, [], and list2 to [1,2,3,8,17,2,4]. Either of the two list could be empty, but you can assume that nether list is null. You are not to create any new nodes. Your method should simply change links of the list to join them together.Explanation / Answer
public class ListTransform {
public static class Node{
public int val;
public Node next;
}
public static class List{
private Node head;
private int count;
List(){
head = null;
count = 0;
}
public void add(int val){
Node temp = new Node();
temp.val = val;
temp.next = null;
if(head == null){
head = temp;
}
else{
temp.next = head;
head = temp;
}
count++;
}
public void transferFrom(List l2){
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = l2.head;
count += l2.count;
l2.count = 0;
l2.head = null;
}
public String toString(){
String ret = "";
Node temp = head;
while(temp != null){
ret = ret.concat(Integer.toString(temp.val) + " ");
temp = temp.next;
}
return ret;
}
}
public static void main(String args[]){
List l1 = new List();
List l2 = new List();
l1.add(12);
l1.add(23);
l1.add(14);
l1.add(18);
l1.add(22);
l2.add(36);
l2.add(24);
l2.add(9);
System.out.println("l1 is " + l1);
System.out.println("l2 is " + l2);
l1.transferFrom(l2);
System.out.println("After transfer from l2 to l1");
System.out.println("l1 is " + l1);
System.out.println("l2 is " + l2);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.