Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method stretch that stretches a linked list of integers by a specified i

ID: 3803478 • Letter: W

Question

Write a method stretch that stretches a linked list of integers by a specified integer value amount, so that each node of the list parameter is represented by amount copies of the node in the list that's returned.

The ListNode class will be accessible when your method is tested:

public class ListNode { int info;

ListNode next;

ListNode(int x){ info = x; }

ListNode(int x, ListNode node){

info = x;

next = node; }

}

Skeleton Code Provided:

public class ListStretch {
public ListNode stretch (ListNode list, int amount){
// replace statement below with code you write
return null;
}
}

For example

returns [1,1,2,2,3,3] since each value is represented by two values in the list returned.

returns [] since an empty/null list has no nodes that are represented in the return list

returns [5,5,5,5,6,6,6,6,8,8,8,8,9,9,9,9]

Explanation / Answer

public ListNode stretch (ListNode list, int amount){
   int i=0;
   List head = list;
   ListNode l = list;
   while(l.next != null){
       i++;
       l = list.next;
   }
   int arr[]=new int[i];
   int k=0;
   l=list;
   while(l.next != null){
       arr[k]=l.data;  
       k++;
       list = list.next;
   }
   int j=0;
   k=0;
   if(i>0){
   while(k<i){
       j=0;
           while(j<amount){
               ListNode new_node = new ListNode(arr[k]);
               new_node.next = list.next;
           list.next = new_node;
           j++;
           list=list.next;
           }
           list = list.next;
           k++;
   }
   }
   return head;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote